C++ recursive solution 12 ms, easy to understand


  • -1
    A
    int sumD(int n) {
        if (n == 0)
            return 0;
        return (n % 10)*(n % 10)+ sumD(n/10);
    }
    
    bool isHappyHelper(int n, std::multimap<int,int> &m) {
        if (n == 1)
            return true; 
        if (m.count(n) > 0)
            return false;
    
        m.insert(std::make_pair(n,0));   
        return isHappyHelper(sumD(n),m);
    }
    
    bool isHappy(int n) {
    
        std::multimap<int,int> m;
        return isHappyHelper(n,m);
    }

Log in to reply
 

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