题目大意
编写一个算法来判断一个数是不是“快乐数”。
一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。
示例:
输入: 19
输出: true
解释:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
思路
如果不是快乐数,所得的数字会出现循环。第一个方法是用HashMap存储已经出现过的数字,这样可以方便地找到循环。第二个方法是利用快慢指针完成一轮循环。
代码一:HashMap
private int count(int n) {
int res = 0;
while(n>0)
{
res+= (n%10) * (n%10);
n/=10;
}
return res;
}
public boolean isHappy(int n) {
//<结果,原数>
boolean flag = false;
HashMap<Integer,Integer> map = new HashMap<>();
while(!flag) {
int res = count(n);
if(res == 1) return true;
if(map.containsKey(res)) return false;
else
{
map.put(res,n);
n = res;
}
}
return flag;
}
运行时间5ms,击败67.31%。
代码二:快慢指针
循环问题,快指针一次走两步,慢指针一次一步, 达到一轮循环。注意快指针的起点要比慢指针前。
private int count(int n) {
int res = 0;
while(n>0)
{
res+= (n%10) * (n%10);
n/=10;
}
return res;
}
public boolean isHappy(int n) {
int fast = count(n), slow = n;
while(fast!=slow) {
slow = count(slow);
fast = count(fast);
fast = count(fast);
}
return slow == 1;
}
运行时间2ms,99.12%。