class Solution {
public static boolean isHappy(int n) {
// 已经计算过的词
Set<Integer> hasCalculateSet = new HashSet<>();
while (n!=1 && !hasCalculateSet.contains(n)){
hasCalculateSet.add(n);
n = getDifferenceValue(n);
}
return n==1;
}
private static int getDifferenceValue(int n) {
int res = 0;
while (n > 0) {
int temp = n % 10;
res += temp * temp;
n = n / 10;
}
return res;
}
}
这儿唯一需要考虑的就是用set集合存储已经计算的数字,防止出现无线循环问题