leetcode 202-- 快乐数
链接: 快乐数
题目描述
思路分析
1、首先我们需要理解题目的意思,就是给的数字按照其个十百可以分别进行进行平方。
2、如果平方后的数字最终结果为1,那么这个数是快乐数。
3、如果最后结果中出现了重复的数字,那么这个数字就不是快乐数,如何判断数字是否重复,那必然得通过hashset。
代码演示
class Solution {
public boolean isHappy(int n) {
HashSet<Integer> hashSet = new HashSet<>();
while (n != 1 && !hashSet.contains(n)){
hashSet.add(n);
n = getNextnumber(n);
}
return n == 1;
}
public int getNextnumber(int n){
int res = 0;
while(n > 0){
int tem = n % 10;
res += tem*tem;
n = n / 10;
}
return res;
}
}