LeetCode – Happy Number (Java)

Write an algorithm to determine if a number is “happy”.

What is an happy number can be shown in the following example:

19 is a happy number
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1

Analysis

The key to solve this problem is the stop condition for the loop.

Java Solution

public boolean isHappy(int n) {
    HashSet<Integer> set = new HashSet<Integer>();
 
    while(!set.contains(n)){
        set.add(n);
 
        n = getSum(n);
 
        if(n==1)
            return true;
    }
 
    return false;
}
 
public int getSum(int n){
    int sum =0;
    while(n>0){
        sum+=(n%10)*(n%10);
        n=n/10;
    } 
    return sum;    
}

3 thoughts on “LeetCode – Happy Number (Java)”

  1. We need a set because we know it will not be a happy number if it’ll return to a previous sum we’ve seen before. This basically means it will run in a continuous loop. A hash could also be used to store the sums previously seen for O(1) lookup time.

Leave a Comment