public class Solution {
public boolean isHappy(int n) {
if(n <= 0)
return false;
HashSet set = new HashSet<>();
int res = n;
while(res > 1) {
if(set.contains(res)) {
return false;
}
set.add(res);
res = helper(res);
}
return true;
}
private int helper(int n) {
int sum = 0;
while(n > 0) {
sum = sum + (int)Math.pow(n%10, 2);
n = n/10;
}
return sum;
}
}
把每次各个digit相加的和存放在hashset中,如果有重复,则证明出现了循环,返回false 。
public class Solution { public boolean isHappy(int n) { if(n <= 0) return false; HashSet set = new HashSet<>();
int res = n;
while(res > 1) {
if(set.contains(res)) {
return false;
}
set.add(res);
res = helper(res);
}
return true;
}
private int helper(int n) {
int sum = 0;
while(n > 0) {
sum = sum + (int)Math.pow(n%10, 2);
n = n/10;
}
return sum;
}
}