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.
我们很难在有限步骤内确定一个数是否是快乐数,但使用排除法的话,我们可以尝试判断一个数不是快乐数。根据题意,当计算出现死循环的时候就不是快乐数。出现死循环的说明产生了相同的结果。我们可以用set来记录所有出现过的数字,然后每出现一个新数字,在set中查找看是否存在,若不存在则加入表中,若存在则跳出循环,并且判断此数是否为1,若为1返回true,不为1返回false。use a set to store the sum of square of previous numbers in each round. If current number is in this set, then this number cannot be "happy" since there must have an endless loop.
Last updated
Was this helpful?