class Solution {
private 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);把每次得到的数加入哈希表中,如果有重复的话,就是有循环,直接false
n = getNext(n);
}
return n == 1;
}
}
202.快乐数
最新推荐文章于 2022-12-18 15:28:07 发布