202. 快乐数

官方题解

https://leetcode-cn.com/problems/happy-number/solution/kuai-le-shu-by-leetcode-solution/

class Solution {
public:
    bool isHappy(int n) {
        unordered_map<int,int> mp;
        while (true) {
            int t=n,w=0;
            while (t) {
                w+=(t%10)*(t%10);
                t/=10;
            }
            if (mp[w]==0) mp[w]=1;
            else return false;
            
            if (w==1) return true;
            n=w;
        }
    }
};

然而我最开始是这么写的,盲猜如果循环没有规律的话,不会超过一般的时间复杂度的,然后就填了1e6的循环,发现401点超时,然后改成1e5就可以了,哈哈,奇奇怪怪的姿势

class Solution {
public:
    bool isHappy(int n) {
        int k=1e5;
        while (k--) {
            int t=n;
            int w=0;
            while (t) {
                w+=(t%10)*(t%10);
                t/=10;
            }
            if (w==1) {
                return true;
            }
            n=w;
        }
        return false;
    }
}; 
posted @ 2020-05-17 21:32  xyee  阅读(121)  评论(0编辑  收藏  举报