""" 0202.1 - Happy Number - Solution 1 - HashSet Cycle Detection """
#####################################################################################
# Imports
#####################################################################################
#####################################################################################
# Classes
#####################################################################################
class Solution:
"""Solution Class"""
def isHappy(self, n: int) -> bool:
"""Happy Number Function"""
seen = set()
while n != 1:
if n in seen:
return False
seen.add(n)
n = sum(int(d) ** 2 for d in str(n))
return True
#####################################################################################
# Functions
#####################################################################################
def testcase():
"""Test Function"""
print(Solution().isHappy(19)) # True
print(Solution().isHappy(2)) # False
print(Solution().isHappy(7)) # True
print(Solution().isHappy(1)) # True
#####################################################################################
# Main
#####################################################################################
if __name__ == "__main__":
testcase()
""" 0202.2 - Happy Number - Solution 2 - Floyd's Cycle Detection """
#####################################################################################
# Imports
#####################################################################################
#####################################################################################
# Classes
#####################################################################################
class Solution:
"""Solution Class"""
def isHappy(self, n: int) -> bool:
"""Happy Number Function"""
def get_next(number: int) -> int:
return sum(int(d) ** 2 for d in str(number))
slow = n
fast = get_next(n)
while fast != 1 and slow != fast:
slow = get_next(slow)
fast = get_next(get_next(fast))
return fast == 1
#####################################################################################
# Functions
#####################################################################################
def testcase():
"""Test Function"""
print(Solution().isHappy(19)) # True
print(Solution().isHappy(2)) # False
print(Solution().isHappy(7)) # True
print(Solution().isHappy(1)) # True
#####################################################################################
# Main
#####################################################################################
if __name__ == "__main__":
testcase()