My C++ solution in 7ms


  • 0
    S
    class Solution {
    public:
        bool isHappy(int n) {
    		vector<int> old;
    		old.push_back(n);
    		do 
    		{
    			n = getDigitsSum(n);
    			if (std::find(old.begin(), old.end(), n) != old.end())
    			{
    				break;
    			}
    			old.push_back(n);
    		} while (n && n!=1);				
    
    		return n==1;
    	}
    
    	int getDigitsSum(int n)
    	{
    		int v = 0;
    		int sum = 0;
    		while (n)
    		{
    			v = n % 10;
    			sum += v*v;
    			n /= 10;
    		}
    		return sum;
    	}
    };

Log in to reply
 

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