Write an algorithm to determine if a number n
is happy.
A happy number is a number defined by the following process:
Return true
if n
is a happy number, and false
if not.
int
→ str
의 과정을 거쳐 1까지 도달하는지 확인하는 문제set()
을 사용했다.class Solution:
def isHappy(self, n: int) -> bool:
if n == 1:
return True
visited = set()
visited.add(n)
while 1:
num = str(n)
n = 0
for w in num:
n += (int(w)**2)
if n in visited:
return False
elif n == 1:
return True
else:
visited.add(n)