10k

202. Happy Number

Question

Write an algorithm to determine if a number n is happy.

A happy number is a number defined by the following process:

  • Starting with any positive integer, replace the number by the sum of the squares of its digits.
  • Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
  • Those numbers for which this process ends in 1 are happy.

Return true if n is a happy number, and false if not.

Algorithm

Nothing special, you follow the requirement and implement it.

Use a set to store the sums to check if there are infinite loop. If so, return false; otherwise continue calculate the sums until sum = 1.

Code

class Solution {
    public boolean isHappy(int n) {
        Set<Integer> set = new HashSet<>();
        int num = calculateSum(n);
    
        while (num != 1) {
            if (!set.add(num)) {
                return false;
            } else {
                set.add(num);
                num = calculateSum(num);
            }
        }
        return true;
    }
    
    private int calculateSum(int n) {
        int sum = 0;
        while (n > 0) {
            int num = n % 10;
            sum += num * num;
            n /= 10;
        }
        return sum;
    }
}
Thoughts? Leave a comment