class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
if n == 1:
return True
def square_each(num): #定义一个用于计算每一位数平方和的函数
sum_n = 0
list_n = list(str(num))
for i in list_n:
sum_n += int(i)**2
# print(i, "-----", sum_n)
return sum_n
count = 0
now_n = n
while count<20 and now_n != 1: #控制循环次数 和跳出条件
now_n = square_each(now_n)
if now_n == 1:
return True
count += 1
return False
202. 快乐数 - 力扣(LeetCode)
思路:模拟过程
把计算每一位数字的平方和的过程封装成一个函数, 在循环里面调用。
二刷提高点:
可以思考一下快乐数的数学性质,写进代码逻辑中。