版权声明:此文章为许诗宇所写,如需转载,请写下转载文章的地址 https://blog.csdn.net/xushiyu1996818/article/details/86536811
题目及测试
package pid202;
/* 快乐数
编写一个算法来判断一个数是不是“快乐数”。
一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。
示例:
输入: 19
输出: true
解释:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 02 = 1
*/
import java.util.List;
public class main {
public static void main(String[] args) {
int [] testTable = {19,10,21,499979};
for (int ito : testTable) {
test(ito);
}
}
private static void test(int ito) {
Solution solution = new Solution();
boolean rtn;
long begin = System.currentTimeMillis();
System.out.print(ito);
System.out.println();
//开始时打印数组
rtn= solution.isHappy(ito);//执行程序
long end = System.currentTimeMillis();
System.out.println("rtn=" );
System.out.print(rtn);
System.out.println();
System.out.println("耗时:" + (end - begin) + "ms");
System.out.println("-------------------");
}
}
解法1(成功,6ms,较慢)
建立一个string类型的hashset,每次循环前看set里是否有这个数,没有则加入,有则说明进入循环,返回false
将integer转为string,再分为char数组,将char-'0'得到char的对应数字,平方后加起来变为now,结束循环
package pid202;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
class Solution {
public boolean isHappy(int n) {
HashSet<String> set=new HashSet<>();
Integer now=n;
while(true){
String string=now.toString();
if(set.contains(string)){
return false;
}
else{
set.add(string);
}
if(now.equals(1)){
return true;
}
char[] chars=string.toCharArray();
Integer sum=0;
for(char nowChar:chars){
int nowInt=nowChar-'0';
sum=sum+nowInt*nowInt;
}
now=sum;
}
}
}
解法2(别人的)
在这里首先了解一个小知识 , 当快乐数始终变不了1 , 陷入无限循环时 , 最终得到的结果就会是4 , 所以只需要判断结果是否等于4 , 如果为4 , 则就不是快乐数
用4代替hashset,提升效率
int Num(int x)
{
int ret=0;
while(x){
ret+=(x%10)*(x%10);
x/=10;
}
return ret;
}
bool isHappy(int n) {
if(n<=0)
return false;
while(n!=1){
n=Num(n);
if(n==4)
return false;
}
return true;
}
解法3(别人的)
快慢指针
public class Solution {
private int calc(int n) {
int next = 0;
while (n>0) {
int digit = n % 10;
n /= 10;
next += digit * digit;
}
return next;
}
public boolean isHappy(int n) {
int slow = n;
int fast = n;
while (true) {
slow = calc(slow);
fast = calc(calc(fast));
if (fast == 1) return true;
if (slow == fast) return false;
}
}
}
总结:
检验循环的方法:hashset,是否为4,快慢指针
得到数的平方和:转为string,拆分char后平方和,或者,每次mod10在/10的平方和