Simple Solution


  • 0
        public static boolean isHappy(int n) {
    		Set<Integer> visited = new HashSet<Integer>();
    		while(n!=1 && !visited.contains(n)) {
    			visited.add(n);
    			int squaresum = 0;
    			while (n>0) {
    				squaresum+=(int)Math.pow(n%10,2);
    				n=n/10;
    			}
    			n=squaresum;
    		}
    		return n==1?true:false;
    	}
    
    1. Use an HashSet to keep track of the visited elements
    2. While n!=1 AND n has not been visited yet:
    3. add n to the HashSet
    4. Compute the sum of squares of each digit in n, by getting the last
      digit with n%10, then removing the last digit with n=n/10
    5. Set n to the computed sum of squares
    6. if n==1 return true else if n has already been visited return false

Log in to reply
 

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