一旦考虑到cycle的问题:可以用快慢指针解决
本题是一个很好的例子,可以用快慢指针判断n在计算过程中会不会回到之前的值
/**
* discuss里的,用set判断重复情况
* Runtime: 1 ms, faster than 81.32%
* Memory Usage: 36 MB, less than 44.52%
*/
class Solution {
public boolean isHappy(int n) {
Set<Integer> set = new HashSet<>();
while (n != 1) {
int temp = 0;
while (n != 0) {
temp += Math.pow(n % 10, 2);
n /= 10;
}
if (!set.add(temp))
return false;
n = temp;
}
return true;
}
}
/**
* discuss中的
* 用快慢指针判断是否循环回到之前的数
* 时间空间复杂度和用set的解法一样
*/
// 写法一
class Solution {
public boolean isHappy(int n) {
int fast = n, slow = n;
do {
slow = compute(slow);
fast = compute(compute(fast));
if (fast == 1)
return true;
} while (slow != fast);
return false;
}
private int compute(int num) {
int res = 0;
while (num != 0) {
res += Math.pow(num % 10, 2);
num /= 10;
}
return res;
}
}
// 写法二
class Solution {
public boolean isHappy(int n) {
int fast = n, slow = n;
while (fast != 1) {
slow = compute(slow);
fast = compute(compute(fast));
if (slow == fast && fast != 1) // 注意这里要判断相等时为不为1,如果为1就还是happy number
return false;
}
return true;
}
private int compute(int num) {
int res = 0;
while (num != 0) {
res += Math.pow(num % 10, 2);
num /= 10;
}
return res;
}
}