Happy Number
Solution in go
func isHappy(n int) bool {
    set := make(map[int]struct{})
    currentDigitSum := n

    for {
        currentDigitSum = digitSquareSum(currentDigitSum)
        if currentDigitSum == 1 {
            return true
        }

        // We have already seen this number
        // and are in a loop.
        if _, ok := set[currentDigitSum]; ok {
            return false
        }

        set[currentDigitSum] = struct{}{}
    }
}

func digitSquareSum(num int) int {
    var result int

    for num > 0 {
        remain := num % 10
        result += remain * remain
        num /= 10
    }

    return result
}
    TheDeveloperCafe © 2022-2024