Leetcode解题: happy number (202)

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: 19 is a happy number

12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

解法1:hashmap

这里需要判断重复的情况,想到用hashmap来存储已经计算过的值。对每一个未访问过的数值,计算位数的平方和。
C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public:
bool isHappy(int n) {
if (n <= 0) {
return false;
}
if (n == 1) {
return true;
}
unordered_map<int, bool> map;
while (n != 1) {
map[n] = true;
int temp = digitSquareSum(n);
if (map[temp]) {return false;}
n = temp;
}
return true;
}
int digitSquareSum(int n) {
if (n == 0 || n == 1) {
return n;
}
int sum = 0;
while (n != 0) {
int digit = n % 10;
sum += digit * digit;
n /= 10;
}
return sum;
}
};

Java

1

解法2:观察规律

看到别人的解法里有这么一个巧妙的方法:可以试试几个会出现loop的数,最后都会出现4。结论是:所有最终会有4的都不是happy number,这样我们就可以把额外的空间要求去除了。
例子如下:
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

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
bool isHappy(int n) {
while (n != 1 && n != 4) {
int t = 0;
while (n) {
t += (n % 10) * (n % 10);
n /= 10;
}
n = t;
}
return n == 1;
}
};