Happy Number

Write an algorithm to determine if a number is "happy". Example: 19 is a happy number
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

  • Time: O(N)
  • Space: O(1)
class HappyNumber {
    Set<Integer> set = new HashSet<>();
    public boolean isHappy(int n) {
        if (set.contains(n)) return false;
        set.add(n);
        int sum = 0;
        while (n > 0) {
            sum += Math.pow(n % 10, 2);
            n = n / 10;
        }
        if (sum == 1) {
            return true;
        } else {
            return isHappy(sum);
        }
    }
}

results matching ""

    No results matching ""