Can any one tell me what is the wrong in this answer/code ?


  • 0
    R
    bool isHappy(int n) {
            set<int> m;
            if (n==1) return true;
            if (m.find(n)!=m.end()) return false;
            m.insert(n);
            int temp=0;
            while(n>0){
                temp+=(n%10)*(n%10);
                n/=10;
            }
            return isHappy(temp);
        }

  • 0
    A

    Declare the set<int> m globally, otherwise, every call of the function will have its own m, and when you search for n in m, you are escentially searching for n in an empty set every time.


  • 0
    U

    try "static set<int> m"


Log in to reply
 

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