主要是用到了鸽巢原理,最后他们一定会重合,我们只需要判断类似,链表的成环相遇的时候是不是1就行了
class Solution {
public:
int bitsum(int n)
{
int sum = 0;
while (n)
{
int a = 0;
a = n % 10;
sum += a * a;
n /= 10;
}
return sum;
}
bool isHappy(int n) {
int fast = bitsum(n);
int slow = n;
while (fast != slow)
{
fast = bitsum(fast);
fast = bitsum(fast);
slow = bitsum(slow);
}
if (fast == 1)
{
return true;
}
else return false;
}
};