My silly but easy to read JAVA solution


  • 0
    Z
    public class Solution {
        public boolean isHappy(int n) {
        	boolean[] array = new boolean[162];
        	int testnumber=0;	
        	do{    		
        		testnumber=CalculateSquareSum(n);
        		if(testnumber==1)return true;
        		if(testnumber<162 && array[testnumber]==true) return false;
        		n=testnumber;
        		if(testnumber<162) array[testnumber]=true;
        	}while(true);   
        }
        
        public static int CalculateSquareSum(int n){
        	int result=0;
        	do{
        		result+=(int)Math.pow(n%10, 2);
        	}while((n/=10)!=0);
        	return result;
        
        }
    }

  • 0
    Z

    I used an array with size 162(9^2+9^2) instead of Hashtable to do the logic.


  • 0
    H

    It's hard to come up with the number 162 before understanding the theoretical support. The HashSet solution is more straight forward.


Log in to reply
 

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