核心思想:使用快慢指针思想找出循环,参考“环形链表”题目
class Solution {
public:
int bitSquareSum(int n) {
int sum = 0;
while(n > 0) {
int bit = n % 10;
sum += pow(bit, 2);
n = n / 10;
}
return sum;
}
/*for example: n = 2
2 4 16 37 58 89 145 42 20 4 16 ...*/
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;
}
};