when to stop when number is not a happy number

后端 未结 4 684
春和景丽
春和景丽 2020-12-22 07:19

A happy number is 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 un

4条回答
  •  臣服心动
    2020-12-22 07:42

    You can detect unhappy numbers with a constant amount of memory. According to Wikipedia, for any positive integer starting point, the sequence will terminate at one, or loop forever at 4, 16, 37, 58, 89, 145, 42, 20, 4. Since no other loops exist, it is easy to test for unhappiness.

    def isHappy(x):
        while True:
            if x == 1:
                return True
            if x == 4:
                return False
            x = nextNumberInSequence(x)
    

提交回复
热议问题