LeetCode 16 - Happy Number

Happy Number

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.

1
2
3
4
5
6
7
8
9
Example:
Input: 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution(object):
def isHappy(self, n):
unique_nums = set()
while True:
sum = 0
while (n):
remainder = n % 10
sum += pow(remainder, 2)
n = n / 10
if (sum == 1):
return True
elif (sum in unique_nums):
return False
else:
n = sum
unique_nums.add(sum)

I found the description of this problem to be lacking. It’s easy to see why something was a Happy Number, but not why a number wasn’t a Happy Number. A number is not a Happy Number if the sum has ever appeared in the past before it reaches 1. As such, you keep track of all sums in a set and as soon as you add a sum that is already in the set then you return False.