My Accepted Solution in JAVA


  • 4
    E
    public class Solution {
        public boolean isHappy(int n) {
            int newN = 0;
        	HashSet<Integer> set = new HashSet<Integer>();
        	
        	while(!set.contains(n)){
        		set.add(n);
        		newN = 0;
        		while(n != 0){
        			newN += (n % 10) * (n % 10);
        			n /= 10;
        		}
        		n = newN;
        		
        		if(n == 1) return true;
        	}
        	
        	return false;
        }
    }

  • 0
    J

    using a hashset is a smart idea. this avoid endless loop. and it is easier to understand than other methods.


Log in to reply
 

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