- 快乐数
思路:
代码:
class Solution {
public:
int getSum(int n){
int sum = 0;
while(n){
sum += (n % 10) * (n %10);
n /= 10;
}
return sum;
}
bool isHappy(int n) {
// 定义快慢指针
int slow = n, fast = n;
while(1){
// slow走一步,fast走两步,最终两者一定会相遇
slow = getSum(slow);
fast = getSum(getSum(fast));
if(slow == fast) // 第一次相遇,slow回滚
{
slow = n;
fast = fast;
while(slow!=fast){
slow = getSum(slow);
fast = getSum(fast);
}
return slow==1;
// 这个循环执行完,两者第二次相遇,也就是环的入口
}
}
return slow==1;
}
};