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++
Java
解法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++