A Simple Recursive Java Solution


  • 1
    H
    public boolean isHappy(int n) {
    	int temp = 0;
    	while (n >= 10) {
    		temp += Math.pow(n % 10, 2);
    		n /= 10;
    	}
    	temp += Math.pow(n % 10, 2);
    	if (temp >= 10) {
    		return isHappy(temp);
    	} else {
    		if (temp == 1) {
    			return true;
    		} else {
    			return false;
    		}
    	}
    }

  • 0
    C

    I find it interesting how this performs faster than making a while loop that has a condition of "n > 0", all things the same.

    Thanks for posting your code!


  • 0
    B

    Input:
    1111111
    Output:
    false
    Expected:
    true
    the answer is wrong?er


Log in to reply
 

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