Java 6ms solution with HashSet


  • 0
    R
    public boolean isHappy(int n) {
    		HashSet<Integer> distinct = new HashSet<>();
    		while(n != 1) {
    			if (distinct.contains(n))
    				return false;
    			distinct.add(n);
    			int sum = 0;
    			while(n > 0) {
    				int remainder = n % 10;
    				sum += remainder * remainder;
    				n = n / 10;
    			}
    			n = sum;
    		}
    		return true;
    	}

Log in to reply
 

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