[LeetCode] 202. Happy Number

Posted codingEskimo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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的主要内容,如果未能解决你的问题,请参考以下文章

40. leetcode 202. Happy Number

202. Happy Number(LeetCode)

LeetCode 202. Happy Number

[LeetCode]202. Happy Number

leetcode 202. Happy Number

Leetcode202 Happy number