一个“快乐数”的定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为1,也可能是无限循环但始终变不到1.如果可以变为1,那么这个数就是快乐数。
实例:
输入:19
输出:true
解释:
1^2 + 9^2 = 82
8^2 + 2 ^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 +0^2 = 1
Way 1:
public int getNext(int num){
int result = 0;
result = (num % 10)*(num % 10);
num = num/10;
if(num == 0){
return result;
}else{
return result+getNext(num);
}
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.isHappy(19));
}
}
Way2:
public class Solution{
public boolean isHappy(int n){
Set<Integer> set = new HashSet<>();
while(n!=1){
int flag = getNext(n);
if(set.contains(flag)){
return false;
}else{
set.add(flag);
n = flag;
}
}
return true;
}
//16
public int getNext(int num){
int result = 0;
result = (num % 10)*(num % 10);
num = num/10;
if(num == 0){
return result;
}else{
return result+getNext(num);
}
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.isHappy(1));
}
}