From 120ab5f7a085003ce03f97d978888cdebd772b9b Mon Sep 17 00:00:00 2001 From: Kiril Kovachev Date: Tue, 30 Apr 2024 17:07:28 +0100 Subject: [PATCH] Solve 202. Happy Number --- python/202_happy_number.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 python/202_happy_number.py diff --git a/python/202_happy_number.py b/python/202_happy_number.py new file mode 100644 index 0000000..cba6475 --- /dev/null +++ b/python/202_happy_number.py @@ -0,0 +1,16 @@ +class Solution: + def isHappy(self, n: int) -> bool: + seen = {n} + while True: + n = self.square_digital_sum(n) + if n in seen: + return n == 1 + seen.add(n) + + @staticmethod + def square_digital_sum(n: int) -> int: + total = 0 + while n > 0: + n, digit = divmod(n, 10) + total += digit**2 + return total