要求:算每一位的平方之和,最后是否回到1
思路:最大数10位,就算10个81也才810,必然会有重复的。我们可以用哈希表记录循环,也可以快慢指针。如果有循环那么相遇时肯定不是1,如果没有循环那么相遇时肯定是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;
}
};