Happy Number
Problem: Happy Number
Since the question mentions non-happy number will loop in a cycle, then we can store visited numbers so that if we get in a loop we can find out. Then we can return our answer by judging whether we are in a loop.
Code in Python:
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
visited = []
while True:
if n == 1:
return True
elif n in visited:
return False
else:
visited.append(n)
sum = 0
while n:
sum += (n % 10) * (n % 10)
n /= 10
n = sum