题目
https://leetcode.com/problems/happy-number/
解题思路
用字典储存出现过的数字。若重复出现,则返回False;若等于1,则返回True。
代码
class Solution(object):
def cal_square_sum(self, n):
num_l = []
while n > 0:
num_l.append(n%10)
n = n/10
res = 0
for i in num_l:
res += i**2
return res
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
d = {}
while n not in d:
d[n] = 0
n = self.cal_square_sum(n)
if n == 1:
return True
return False