0-3ms non-recursive O(1) space C++ solution


  • 0
    W
            // 811 is enough since n < 9999999999 (sum of squres = 810). 
            // This tends to be faster than unordered_map for obvious reasons.
            bool mymap[811];
            for (short jj = 0; jj < 811; mymap[jj++] = false);
            
            short total{};
            
            do {
                while (n) {
                    total += (n % 10)*(n % 10);
                    n /= 10;
                }
    
                if (total == 1)
                    return true;
                else if (mymap[total]++)
                    return false;
    
                n = total;
                total = 0;
            } while (true);
    

Log in to reply
 

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