Happy number
- Happy to get away
Title Description
编写一个算法来判断一个数是不是“快乐数”。
一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。
Examples
- Input: 19
- Output: true
- Explanation:
- 1^2 + 9^2 = 82
- 8^2 + 2^2 = 68
- 6^2 + 8^2 = 100
- 1^2 + 0^2 + 0^2 = 1
Analytical title
- When the digital loop begins, there is no way to get that number 1, that it is very happy
- I used a resultNums to store each number, if the number appeared
- Then the end of the cycle returns false
Code
public boolean isHappy(int n) {
List<Integer> resultNums = new ArrayList<>();
while( n != 1 ){
n = squareEveryNum(n);
if( resultNums.contains(n) ){
return false;
}
resultNums.add(n);
}
return true;
}
private int squareEveryNum(int n) {
int res = 0;
do{
res += ( n%10 ) * ( n%10 );
} while( (n/=10) != 0 );
return res;
}