-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathhappy-number.py
More file actions
34 lines (25 loc) · 807 Bytes
/
happy-number.py
File metadata and controls
34 lines (25 loc) · 807 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution:
def isHappy(self, n: int) -> bool:
def next_num(num):
return sum(int(i) ** 2 for i in str(num))
left, right = n, next_num(next_num(n))
while left != 1:
if left == right:
return False
left, right = next_num(left), next_num(next_num(right))
return True
def isHappyStraightforward(self, n: int) -> bool:
seen = set()
while n != 1:
if n in seen:
return False
seen.add(n)
n = sum(int(i) ** 2 for i in str(n))
return True
class TestSolution:
def setup(self):
self.sol = Solution()
def test_case1(self):
assert self.sol.isHappy(19)
def test_case2(self):
assert not self.sol.isHappy(2)