C++ Solution. No Hashing required. 3ms solution.


  • 0
    K

    There is an interesting pattern here that if there is a 5 in the units place of the sum(not the original number itself), then there will be a loop.

    class Solution {
    public:
        int squareDigits(int n) {
            int sum = 0;
            while(n) {
                sum += (int)(pow(n%10, 2));
                n /= 10;
            }
            
            return sum;
        }
        
        bool isHappy(int n) {
            while(n) {
                n = squareDigits(n);
                if(n == 1)
                    return true;
                if(n%10 == 5)
                    return false;
            }
            return false;
        }
    };
    

Log in to reply
 

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