Happy Number

Happy Number

Coding Solution

·

1 min read

Problem

Write an algorithm to determine if a number is happy. A happy number is a number where the sum of the squares of each of its digits is found repeatedly till the result is 1. This is similar to the Leetcode Problem - Happy Number

Approach

The approach would be defining a hash set which would store the summation of each of the digits. It would return false if the hash set already contains the result. This will be in loop till the result equals to 1 and then we return true.

class Solution {
    public boolean isHappy(int n) {
        HashSet<Integer> set = new HashSet<Integer>();
        set.add(n);
        while (n != 1) {
            int result = 0;
            while (n != 0) {
                result += Math.pow(n % 10, 2);
                n /= 10;
            }
            if (set.contains(result)) {
                return false;
            }
            set.add(result);
            n = result;
        }
        return true;
    }
}

Do have a look at the discuss section for more optimized solutions if available - LeetCode Discuss