Simple Java technique(Unhappy numbers follow cycle -> 4, 16, 37, 58, 89, 145, 42, 20, 4...)


  • 2
    V

    class Solution {

    public boolean isHappy(int n) {
        int sum = 0;
        while(n>0)
        {
            int x = n%10;
            sum = sum + (x*x);
            n = n/10;
        }
        
        if(sum == 1)
        {
            return true;
        }
        
        else if(sum == 4)
        {
            return false;
        }
        
        return isHappy(sum);
    }
    

    }


Log in to reply
 

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