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
}
Subscribe via email

Get notified once/twice per month when new articles are published.

Copyright © 2022 - 2024 TheDeveloperCafe.
The Go gopher was designed by Renee French.