
关键是怎么去判断循环:
class Solution {
public boolean isHappy(int n) {
HashSet<Integer> set = new HashSet<>();
while (n != 1 && !set.contains(n)) {
set.add(n);
n = getNum(n);
}
return n == 1 ;
}
/**
* 19 -> 1^2 + 9^2 = 82
*/
private int getNum(int n) {
int totalSum = 0;
while (n > 0) {
int add = n % 10;
n = n / 10;
totalSum = n * n;
}
return totalSum;
}
}
第二次写的,使用的是hash表进行判断循环。
但是写的时候,由于过于自信了,但是还是有小问题出现:比如说私有方法忘记了返回值,忘记把数放到hash表里面。
下次需要注意这些问题:“无论会不会,都需要按照自己的想法一步一步来。”
附上代码:
class Solution {
public boolean isHappy(int n) {
Set<Integer> set = new HashSet<Integer>();
while ( n != 1 && !set.contains(n)){
set.add(n);
n = getNum(n);
}
return n ==1;
}
private int getNum(int n){
int total = 0;
int num = 0;
while(n != 0){
num = n % 10;
n = n / 10;
total += num * num;
}
return total;
}
}