My simple c++ solution 4ms with unordered_set.


  • 2

    Using a unordered_set STL to improve the speed of detecting loop.

    class Solution {
    public:
        bool isHappy(int n) {
            unordered_set<int> s;
            while (n != 1 && s.find(n) == s.end()) {
                s.insert(n);
                int tmp = 0;
                while (n != 0) {
                    tmp += ((n%10)*(n%10));
                    n /= 10;
                }
                n = tmp;
            }
            if (n == 1) return true;
            else return false;
        }
    };

Log in to reply
 

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