Created
July 9, 2022 23:39
-
-
Save wanderindev/5ff92ee998cfe79d314ef00d92b2dab6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution(object): | |
def sum_of_squares(self, n): | |
result = 0 | |
while n > 0: | |
digit = n % 10 | |
n = n // 10 | |
result += digit ** 2 | |
return result | |
def is_happy(self, n): | |
""" | |
:type n: int | |
:rtype: bool | |
""" | |
visited = set() | |
while n != 1 and n not in visited: | |
visited.add(n) | |
n = self.sum_of_squares(n) | |
return n == 1 | |
# Test cases | |
sol = Solution() | |
n = 19 | |
assert sol.is_happy(n) | |
n = 2 | |
assert not sol.is_happy(n) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment