Recursive Solution by Java in 8ms


  • 0
    S
         HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
    	 public  boolean isHappy(int n) {
    		 String str=n+"";
    		 char[] arr=str.toCharArray();
    		 int result=0;
    		 for(int i=0;i<arr.length;i++){
    			 int tmp=Integer.parseInt(new StringBuffer().append(arr[i]).toString());
    			 result+=tmp*tmp;
    			
    		 }
    		 if(result==1)
    			 return true;
    		 if(map.containsValue(result))
    		 {
    			 return false;
    		 }
    		 map.put(result, result);
    			 return isHappy(result);
    	 }
    

Log in to reply
 

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