Easy-understand solution with code comments (JAVA)


  • 1
    public class Solution {
        public boolean isHappy(int n) {
            //edge checked
            if(n < 1){
                return false;
            }
            //use array store squares value of 0-9 to reduce calculation
            int[] squares = new int[]{0,1,4,9,16,25,36,49,64,81};
            int sum = 0;
            //use for checking cycle
            Set<Integer> cyc = new HashSet<Integer>();
            while(n != 1){
                //return false if find cycle
                if(cyc.contains(n)){
                    return false;
                }
                cyc.add(n);
                
                while(n != 0){
                    sum += squares[n % 10];
                    n = n / 10;
                }
                //set n to be next number
                n = sum;
                sum = 0;
            }
            
            return true;
        }
    }

Log in to reply
 

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