Clear C++ Solution


  • 1
    C
    class Solution {
    public:
        bool isHappy(int n) {
            map<int,int> temp;
            while(true){
                if(n==1)
                    return true;
                if(temp[n]==1)
                    return false;
                temp[n]++;
                n = Caculate(n);
            }
        }
        int Caculate(int n){
            int ret=0;
            while(n!=0){
                ret+=(n%10)*(n%10);
                n=n/10;
            }
            return ret;
        }
    };
    

    Thanks to samoshka ,the code has been improved.

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

  • 1
    S

    I think unordered_set would be better in this case.
    with map you have logarithmic insert/lookup time, plus why would you need to store values, you only need to know whether you have seen the number or not.


  • 0
    C

    Yes,you are right.
    I have improved the code.
    Thanks a lot.


Log in to reply
 

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