leetcode 202 Happy Number

python:

class Solution:
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        check = [n]
        while (n != 1):
            t = 0
            for j in str(n):
                t += int(j) ** 2
            n = t            
            if n in check:
                return False
            check.append(t)
        return True

c++:

class Solution {
public:
    bool isHappy(int n) {
        vector<int> nums;
        nums.push_back(n);
        while (n != 1){
            int t = 0;
            while(n){
                t += (n%10) * (n%10);
                n = n/10;
            }
            n = t;
            for (int i=0; i<nums.size(); i++){
                //cout << nums[i];
                if(nums[i] == n)
                    return false;
            }
            nums.push_back(n);
        }
        return true;
    }
};

猜你喜欢

转载自blog.csdn.net/MRxjh/article/details/82863224