Simple 3ms C++ solution!


  • 0
    K
    class Solution {
    public:
        bool isHappy(int n) {
            if (n == 0) return false;
            if (n == 1) return true;
            if (n == 4) return false;
            int num = 0;
            string s = to_string(n);
            for (auto a:s) {
                num += (a - '0') * (a - '0');
            }
            return isHappy(num);
        }
    };
    

    The trick is to use string instead of mod to get every digit.


Log in to reply
 

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