码迷,mamicode.com
首页 > 移动开发 > 详细

[LeetCode] 202. Happy Number

时间:2020-04-06 09:24:09      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:lock   starting   equal   lse   利用   any   solution   说明   ati   

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

标签:lock   starting   equal   lse   利用   any   solution   说明   ati   

原文地址:https://www.cnblogs.com/codingEskimo/p/12640422.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!