Description
Write an algorithm to determine if a number is “happy”.
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example
Input: 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
Code
我们先来看一个不是开心数的例子
以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
8^2 + 9^2 = 145
1^2 + 4^2 + 5^2 = 42
4^2 + 2^2 = 20
2^2 + 0^2 = 4
从上面的过程我们可以看到如果不是开心数,那对每位平方求和后得到的数字会出现循环的情况,即之前出现的数会再次出现。所以我们可以借助数据结构set或者map来记录每一步骤求和后的数字,在加入之前先判断是否为1,如果为1,则返回true。然后判断是否在map中已经存在,存在证明存在循环,返回false。否则把它加入到map中。
class Solution {
public boolean isHappy(int n) {
Map<Integer,Integer> map = new HashMap<>();
// 如果n=1,直接返回true
if(n == 1){
return true;
}
while(n!=1) {
int sum = 0;
// 计算每一位的数字的平方,然后求和
while( n!=0){
sum += (n % 10) * (n % 10);
n/=10;
}
if(sum == 1){
return true;
}
if(map.containsKey(sum)){
return false;
}else{
map.put(sum,1);
}
n = sum;
}
return false;
}
}