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.


Solution


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
.