12ms c++ sol. Use set for more efficient search


  • 0
    C
    class Solution {
    public:
      bool isHappy(int n) {
    
        set<int> registed_nums;
        while (n != 1) {
    
          if (registed_nums.find(n) != registed_nums.end())
            return false;
          else
            registed_nums.insert(n);
    
          int new_n = 0;
          while (n != 0) {
    
            new_n += (n % 10) * (n % 10);
            n /= 10;
          }
    
          n = new_n;
        }
    
        return true;
      }
    };

  • 0
    R

    unordered_set should be quicker


Log in to reply
 

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