[LeetCode]#202. Happy Number
1 min readMar 16, 2020
Environment: Python 3.7
Key technique: Divide-and-conquer algorithm
Example:
Input: 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
Analysis: There are two functions in the code. One is for computing square sum, and another is for judging Happy number or not.
Solution:
class Solution:
def Sum(self,num):
str_num=str(num)
res=0
for i in str_num:
res+=(int(i)**2)
return res
def isHappy(self, n: int) -> bool:
Table=[]
while n not in Table:
Table.append(n)
n=self.Sum(n)
if(n==1):
return True
break
if n in Table:
return False
Submitted result:
lesson learn:
We can use ‘self.’ for using another function.
Reference:
https://leetcode.com/problems/happy-number/discuss/538336/Python-Easy