Simple Java solution


  • 0
    L
     public boolean isHappy(int n) {
            Set<Integer> set = new HashSet<Integer>();
            while(n!=1 || set.contains(n)) {
                if(set.contains(n) || (n!=1 && n<=0)) {
                    //cycle or negative.
                    return false;
                }
                set.add(n);
                
                int temp = n ;
                int sum = 0;
                while(temp!=0) {
                    sum += Math.pow(temp%10,2);
                    temp = temp/10;
                }
                n = sum;                
            }
            return true;
        }
    

Log in to reply
 

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