Contents

202. Happy Number

Automatic Translation

This article has been translated automatically from Russian to English. The original is available in Russian.

Solution to problem 202 “Happy Number” from https://leetcode.com


Problem Statement

Happy numbers - these are numbers that can be checked with the following algorithm: the number is positive, add the squares of all its digits, repeat the process until the sum becomes equal to 1 (if the algorithm loops - the numbers are not happy).

Example

Input: 19
Output: true
Explanation:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1

Solution

The solution idea - check straightforwardly.

For this, we create a collection where the key will be the number (sum of squares of digits of number n) - the value is always true. Start a loop with condition n!=1 (n not equal to one). In the loop, calculate the sum of squares of digits.

Then check - is this sum already in the previously created collection:

  • If this sum has already appeared, it means we’ve looped and the number is not happy.
  • If the sum is not in the collection - add it to the collection.

If we exit the loop - it means the sum of squares became equal to one and the original number was happy.

func isHappy(n int) bool {
    if n <=0 {
        return false
    }
    used := make(map[int]bool)
    used[n] = true
    for n!=1 {
        k:= n
        sum := 0
        for k>0 {
            w:=k%10
            k = k/10
            sum +=w*w
        }
        if _, ok := used[sum]; ok {
            return false
        }
        used[sum] = true

        n = sum
    }

    return true
}