Problem : https://leetcode.com/problems/happy-number/
class Solution:
def isHappy(self, n: int) -> bool:
# use hashset to avoid looping in a cycle
seen = set()
while n not in seen:
seen.add(n)
nextNum = 0
while n:
t = n % 10
nextNum += t * t
n = n // 10
n = nextNum
if n == 1:
return True
return False
No comments:
Post a Comment