题目链接:https://leetcode-cn.com/problems/happy-number/
一道简单题,但是踩了十分钟的坑
哈希表标记出现与否,最开始用的bool数组,结果超时。之后看题解改成了map,就AC了。记录一下自闭时刻
代码如下:
class Solution {
public:
int findsquare(int x) {
int res = 0;
while(x) {
int t = x % 10;
res += t * t;
x /= 10;
}
return res;
}
bool isHappy(int n) {
map<int, bool>cnt;
while(1) {
if(cnt[n]) {
return false;
} else if(n == 1) {
return true;
} else {
cnt[n] = true;;
}
n = findsquare(n);
cout << n << endl;
}
}
};