Ac solution code


  • 0

    The basic idea is using a HashSet to check if the current sum result already exists in the previous results, as the following.

    Non-recursive Solution:

    public boolean isHappy(int n) {
    	Set<Integer>set = new HashSet<Integer>();
    	while (!set.contains(n)) {
    		set.add(n);			
    		int sum = 0;
    		while (n != 0) {
    			sum += Math.pow(n % 10, 2); 
    			n /= 10;
    		}
    		n = sum;
    	}
    	return set.contains(1);
    }
    

    Recursive Solution:

    private Set<Integer>set = new HashSet<Integer>();
    public boolean isHappy(int n) {
    	if (set.contains(n)) return (n==1);
    	else set.add(n);	
    	int sum = 0;
    	while (n != 0) {
    		sum += Math.pow(n % 10, 2);
    		n /= 10;
    	}
    	return isHappy(sum);
    }

Log in to reply
 

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