class Solution:
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
# 考虑递归的终止条件,不能收敛为 1 的数字怎么办?
# 不能收敛为1 的数字一般都是循环结构,寻找数学规律
# method one 字符串与整数的转换
# if n < 10:
# if n == 1 or n == 7:
# return True
# else:
# return False
# return self.isHappy(sum([int(i)**2 for i in str(n)]))
# method two 地板除与取余,效率更高
if n < 10:
if n == 1 or n == 7:
return True
else:
return False
new_n = 0
while n:
new_n += (n % 10)**2
n //= 10
return self.isHappy(new_n)
leetcode 202 Happy Number 快乐数 python 多种实现,最简代码
猜你喜欢
转载自blog.csdn.net/huhehaotechangsha/article/details/80820144
今日推荐
周排行