202. 快乐数
编写一个算法来判断一个数 n 是不是快乐数。
「快乐数」 定义为:
- 对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。
- 然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。
- 如果这个过程 结果为 1,那么这个数就是快乐数。
如果 n
是 快乐数 就返回 true
;不是,则返回 false
。
示例 1:
输入:n = 19
输出:true
解释:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
示例 2:
输入:n = 2
输出:false
提示:
记录题解()
import java.util.HashMap;
import java.util.Map;
public class HappyNumber{
public static void main(String[] args) {
Solution solution = new HappyNumber().new Solution();
System.out.println(solution.isHappy(2));
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public boolean isHappy(int n) {
Map<Integer,String> map = new HashMap();
while (true){
String s = String.valueOf(n);
n = 0;
for (int i = 0; i < s.length(); i++) {
int c = (int) Math.pow(s.charAt(i)-48,2);
n += c;
}
if (!map.containsKey(n)){
map.put(n,null);
}else {
return false;
}
if (n == 1) return true;
}
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
力扣官方题解(弗洛伊德查找算法)
class Solution {
public int getNext(int n) {
int totalSum = 0;
while (n > 0) {
int d = n % 10;
n = n / 10;
totalSum += d * d;
}
return totalSum;
}
public boolean isHappy(int n) {
int slowRunner = n;
int fastRunner = getNext(n);
while (fastRunner != 1 && slowRunner != fastRunner) {
slowRunner = getNext(slowRunner);
fastRunner = getNext(getNext(fastRunner));
}
return fastRunner == 1;
}
}