🙃 A pretty easy java solution.


  • 0
    L

    you will find that any unhappy number will have the same step that the number equals 4, then loops endlessly.

    class Solution {
        public boolean isHappy(int n) {
            int sum = 0;
            while (n > 0) {
                sum += Math.pow(n % 10, 2);
                n /= 10;
                if (n == 0) {
                    if (sum == 1) return true;
                    if (sum == 4) return false;
                    n = sum;
                    sum = 0;
                }
            }
            return false;
        }
    }
    

Log in to reply
 

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