My Java Solution


  • 0
    U
    import java.util.HashSet;
    import java.util.Set;
    import java.util.Stack;
    
    public class Solution {
        public boolean isHappy(int n) {
    	       
    		 Set<Integer> savedSums = new HashSet<Integer> ();
    		 
    		 while (n != 1) {
    			 
    			 int temp = calc(n);
    			 
    			 if (!savedSums.contains(temp)) {
    				 savedSums.add(temp);
    			 }
    			 else {
    				 // repeating sum
    				 return false;
    			 }
    			 
    			 n = temp;
    		 }
    		 
    		 return true;
    	 }
    	
    	 public int calc(int n) {
    		 
    		 Stack<Integer> stack = new Stack<Integer> ();
    		 int sum = 0;
    		 
    		 while (n > 0) {
    			 stack.push(n % 10);
    			 n = n / 10;
    		 }
    		 
    		 while (!stack.isEmpty()) {
    			 int temp = stack.pop();
    			 sum += temp * temp;
    		 }
    		 
    		 return sum;
    	 }
    }

Log in to reply
 

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