Simple C++ Solution Using Hash Set


  • 0
    M
    #include <cmath>
    
    class Solution {
    public:
        bool isHappy(int n) {
            unordered_set<int> s;
            while (n != 1) {
                if (s.find(n) != s.end()) return false;
                s.insert(n);
                int sum = 0;
                while (n) {
                    sum += (n % 10) * (n % 10);
                    n /= 10;
                }
                n = sum;
            }
            return true;
        }
    };
    

Log in to reply
 

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