202. 快乐数 - 力扣(LeetCode)
思路:
可以借用判断链表是否有环的思想:
- 定义快慢指针(两个变量赋值就行)
- 快指针走两次,慢指针走一次
- 快慢指针相遇,看是不是等于一
public int bitSum(int n){
int sum = 0;
while(n != 0){
int m = n % 10;
sum += m * m;
n /= 10;
}
return sum;
}
public boolean isHappy(int n) {
int fast = bitSum(n);
int slow = n;
while(slow != fast){
slow = bitSum(slow);
fast = bitSum(bitSum(fast));
}
return slow == 1;
}