思路:
用哈希集合检测循环。
根据我们的探索,我们猜测会有以下三种可能。
- 最终会得到 1。
- 最终会进入循环。
- 值会越来越大,最后接近无穷大。
题解:
class Solution {
public int getNext(int n) {
int totalSum = 0;
while (n > 0){
int d = n % 10;
n = n/10 ;
totalSum += d * d ;
}
return totalSum;
}
public boolean isHappy (int n) {
Set<Integer>seen = new HashSet<>();
while (n !=1 && !seen.contains(n)){
seen.add(n);
n = getNext(n);
}
return n == 1;
}
}