philosyang.com

202. Happy Number

note: can also use the Floyd’s cycle detection algo.

1class Solution:
2    def isHappy(self, n: int) -> bool:
3        seen = set()
4        while n != 1 and n not in seen:
5            seen.add(n)
6            n = sum((int(ch) ** 2) for ch in str(n))
7
8        return n == 1

#Neetcode150 #Hashing #Python