No need HashSet, 2 ms, easy to understand


  • 0
    X

    The intuition is:
    if n has only 1 digit, then 1 or 7 can be true(this is the result of observation).
    if n >= 10, then we do the sum operation until n is less than 10.

    class Solution {
        public boolean isHappy(int n) {
            if(n == 1) {
                return true;
            }
            
            while(n >= 10) {
                int sum = 0;
                int tmp = n;
                while(tmp > 0) {
                    sum += (tmp % 10) * (tmp % 10);
                    tmp = tmp / 10;
                }
                n = sum;
            }
            
            return n == 1 || n == 7;
        }
    }
    

Log in to reply
 

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