题目:编写一个算法来判断一个数是不是“快乐数”。
一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。
示例:
输入: 19
输出: true
解释:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
思路:我自己想的是取出n的各个位上的数求出其平方和,判断是否等于1,如果不是的话继续求解。但这样耗费时间长可能容易陷入死循环。后来参考了网上大神的写法。以下代码基本的思路是一样的,不过是使用了HashSet存放已经出现过的数,防止陷入死循环。
大神代码:
class Solution {
public boolean isHappy(int n) {
if(n<1)
{return false;}
HashSet<Integer>set=new HashSet<>(32); //创建HashSet,但是不懂大小为什么是32
int tem;
int sum;
while (n != 1 && !set.contains(n))
{
set.add(n);
sum=0;
while(n>0)
{
tem=n%10;
n=n/10;
sum=sum+tem*tem;
}
n=sum;
}
return n==1;
}
}
思路:这是在网上找的另外一个代码。执行速度也是最快的,但是有些看不懂。解释中说如果4次循环过程中,每一次所得数字中都不收敛于1,则判断该数字不是一个“快乐的数”。不太懂。
代码:class Solution {
public boolean isHappy(int n) {
if (n == 0)
return false;
return testhappy(0, n);
}
private static boolean testhappy(int number, int n) {
int sum = n;
int add = 0;
boolean hasone = false;
while (sum != 0) {
int square = (sum % 10) * (sum % 10);
add += square;
sum = sum / 10;
if (sum % 10 == 1) { //多次出现的整除10与1进行判断是用来干什么?
hasone = true;
}
}
number++;
int test = add;
while (test != 0) {
if (test % 10 == 1) {
hasone = true;
}
test = test / 10;
}
if (hasone == false && number > 4)
return false;
if (add != 1 || add % 10 != 1) {
boolean istrue = testhappy(number, add);
if (istrue)
return true;
} else {
return true;
}
return false;
}
}
执行用时最快:
思路:
class Solution {
public boolean isHappy(int n) {
if (n == 1)
return true;
int result = 0;
while (true) {
while (n > 0) {
result += Math.pow(n % 10, 2);
n /= 10;
}
if (result == 1) {
return true;
} else if (result == 4) {
return false;
} else {
n = result;
result = 0;
}
}
}}