题目链接
https://leetcode-cn.com/problems/happy-number/
解题思路
- 设置两个指针;
- 指针一每次都求下一个平方和;
- 指针二每次都求辖下一个平方和;
- 如果是快乐数,两个指针会在1相遇;
- 如果不是快乐数,两个指针会在循环的某一处相遇。
代码
class Solution {
public:
int bitSquareSum(int n) {
int sum = 0;
while(n > 0)
{
int bit = n % 10;
sum += bit * bit;
n = n / 10;
}
return sum;
}
bool isHappy(int n) {
int slow = n, fast = n;
do{
slow = bitSquareSum(slow);
fast = bitSquareSum(fast);
fast = bitSquareSum(fast);
}while(slow != fast);
return slow == 1;
}
};