https://leetcode-cn.com/problems/happy-number/
同循环链表类似,还是快慢指针
如果会无限循环,快的会追上慢的,否则就是快乐数
while(1)是因为要么肯定追上了,要么就是快乐数总会跳出来
class Solution {
public:
int trans(int n) {
int res = 0;
while (n) {
res += (n % 10)*(n % 10);
n /= 10;
}
return res;
}
bool isHappy(int n) {
int fast = n;
int slow = n;
while (1) {
fast = trans(fast);
fast = trans(fast);
slow = trans(slow);
if (fast == 1 || slow == 1) return 1;
if (fast == slow && fast != 1) return 0;
}
return 0;
}
};