题目描述:
编写一个算法来判断一个数是不是“快乐数”。
一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直
到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。
示例:
输入: 19 输出: true
思路:一般这种算法题都是有一定技巧规律的,先耐心写几个数试着算一下。就拿这道题来说,我们先随意拿几个数来举例
如 11
1^2 + 1^2 = 2
2^2 =4
4^2 = 16
1^2 + 6^2 = 37
3^2 + 7^2 = 58
5^2 + 8^2 = 89-------------------------------------89循环
8^2 + 9^2 = 145
1^2 + 4^2 + 5^2 = 42
4^2 + 2^2 = 20
2^2 = 4-------------------------------又回到4 继续循环,所以不是快乐数
如 22
2^2 + 2 ^2 = 8
8^2 = 64
6^2 + 4^2 = 52
5^2 + 2^2 = 29
2^2 + 9^2 = 85
8^2 + 5^2 = 89-----------------------89 上个非快乐数也出现了89,一直循环,所以不是
如 12
1^2 + 2^2 = 5
5^2 = 25
2^2 + 5^2 = 29
2^2 + 9^2 = 85
8^2 + 5^2 = 89-----------------------循环,非快乐数
通过以上三个数,我们发现只要是非快乐数都会出现89
所以最简单直观的方法
解法一:
public class Solution {
public boolean isHappy(int n){
while(true){
int flag = getNext(n);
if(flag == 1){
return true;
}else{
n = flag;
if(n == 89){
return false;
}
}
}
}
public int getNext(int n){
int result = 0;
result = result + ((n%10)*(n%10));
n = n / 10;
if(n == 0){
return result;
}else{
return result + getNext(n);
}
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.isHappy(19)); //true
}
}
解法二:
public class Solution {
public boolean isHappy(int n){
Set<Integer> set = new HashSet<>(); //哈希动态存放数组
while(n!=1){
int flag = getNext(n);
if(set.contains(flag)){ // flag 如果在数组中表示将一直循环
return false;
}else{
set.add(flag); // 将flag 加入到数组中
n = flag;
}
}
return true;
}
public int getNext(int n){
int result = 0;
result = result + ((n%10)*(n%10));
n = n / 10;
if(n == 0){
return result;
}else{
return result + getNext(n);
}
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.isHappy(20)); //false
}
}