Accepted Java solution


  • 0
    S

    I had some confusion on when to stop the calculation in the case where the number wasn't a happy number. After looking at some of the discuss solutions, I was able to understand it.

    Set stores the squared sum of the digits. If we come across a sum that already exists in the set , it means we ll be stuck in an infinite cycle of calculation.

    For e.g. for the no '15', we have the sums 26, 40, 16, 37, 58, 89, 145, 42, 20, 4, and finally 16 which is already present in the set . Further calculation will result in the same sums. We need to return false at this point.

     public boolean isHappy(int n) 
        {
            Set<Integer> setOfSums = new HashSet<>();
            int copy = n;
            while(copy!=1)
            {
                int sum = 0;
                while(copy>0)
                {
                    int rem = copy%10;
                    sum += Math.pow(rem,2);   
                    copy = copy/10;
                }
                if(setOfSums.contains(sum))
                {
                    return false;
                }
                setOfSums.add(sum);
                copy = sum;
            }
            return true;
        }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.