// 快慢指针
public boolean isHappy(int n) {
if (n == 1) {
return true;
}
int slow = n, fast = n;
do {
slow = bitSquareSum(slow);
fast = bitSquareSum(fast);
fast = bitSquareSum(fast);
} while (slow != fast);
return slow == 1;
}
private int bitSquareSum(int n) {
int sum = 0;
while (n > 0) {
sum += Math.pow(n % 10, 2);
n = n / 10;
}
return sum;
}
// 集合
public boolean isHappy2(int n) {
Set<Integer> set = new HashSet<>();
int m = 0;
while (true) {
while (n != 0) {
m += Math.pow(n % 10, 2);
n = n / 10;
}
if (m == 1) {
return true;
}
if (set.contains(m)) {
return false;
} else {
set.add(m);
n = m;
m = 0;
}
}
}
网友评论