快乐数

题目:

编写一个算法来判断一个数 n 是不是快乐数。
「快乐数」定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。如果 可以变为 1,那么这个数就是快乐数。
如果 n 是快乐数就返回 True ;不是,则返回 False 。

思路: 检测重复使用hashset

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public boolean isHappy(int n) {
HashSet<Integer> myset = new HashSet<>();
myset.add(n);
while(n!=1){
// System.out.println(n);
n = next(n);
if(myset.contains(n)){
return false;
}
myset.add(n);
}
return true;

}

public int next(int n){
int res=0;
while(n!=0){
res += (n%10)*(n%10);
n = n/10;
}
return res;
}
}
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!

扫一扫,分享到微信

微信分享二维码
  • © 2020 Zhang-Ke
  • Powered by Hexo Theme Ayer
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信