[LeetCode] 202. 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.

Example:

Input: 19

Output: true

Explanation:

12 + 92 = 82

82 + 22 = 68

62 + 82 = 100

12 + 02 + 02 = 1


这道题提示会有infinate loop,这就说明是个cycle,利用这一点,需要建立一个set,把中间的每个得到的number都加到这个set里面,如果已经有了,就说明这是个cycle,直接return false,不然会得到1。只要有cycle就要想到set或者cycle list。

注意一个小细节 divmod的应用

class Solution:
    def isHappy(self, n: int) -> bool:
        seen = set()
        while n != 1 and n not in seen:
            seen.add(n)
            n = self.caculate_next(n)
        return True if n == 1 else False
            
    def caculate_next(self, n: int) -> int:
        total_sum, num = 0, n
        while num > 0:
            num, digit = divmod(num, 10)
            total_sum += digit**2
        return total_sum
        

[LeetCode] 202. Happy Number

上一篇:手机APP无法抓包HTTPS解决方案


下一篇:Android Studio中Make Project、Clean Project、Rebuild Project 的作用