Data Structure & Algorithm: Level-1 Problem #14. Happy Number

In number theory, a happy number is a number which eventually reaches 1 when replaced by the sum of the square of each digit. For instance, 13 is a happy number because 12 + 32 = 10 and  12 + 02 = 1. On the other hand, 4 is not a happy number because the sequence starting with 42 = 16 and 12 + 62 = 37 eventually reaches 22 + 02 = 4, the number that started the sequence, and so the process continues in an infinite cycle without ever reaching 1. A number which is not happy is called sad or unhappy.

Given a number, find out whether it is a happy number or not.

Sample Input: 28

Sample Output: Yes

Given number 28, we can reach 1 as follows: 28 → 2²+8²=68 → 6²+8²=100 → 1²+0²+0² = 1. Therefore 28 is a happy number.


数据结构和算法:初级练习题 #14 – 快乐数


快乐数有以下的特性:在给定的进位制下,该数字所有数位(digits)的平方和,得到的新数再次求所有数位的平方和,如此重复进行,最终结果必定为 1。

在十进位下,100以内的快乐数有:1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100。

输入样例:28

输出样例:Yes

按照快乐数的规则,从数字28可以得到1如下:28 → 2²+8²=68 → 6²+8²=100 → 1²+0²+0² = 1。所以28是快乐数。


Python Solution

Happy Number