-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path202.py
32 lines (29 loc) · 925 Bytes
/
202.py
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
# https://neetcode.io/problems/non-cyclical-number
# https://leetcode.com/problems/happy-number/description/
# O(logn) time, O(logn) space
class Solution:
def isHappy(self, n: int) -> bool:
visited = set()
while True:
currSum = 0
for c in str(n):
currSum += int(c) ** 2
if currSum == 1:
return True
if currSum in visited:
return False
visited.add(currSum)
n = currSum
# O(logn) time, O(1) space
class Solution:
def isHappy(self, n: int) -> bool:
def sumSquares(num):
currSum = 0
for c in str(num):
currSum += int(c) ** 2
return currSum
slow, fast = n, sumSquares(n)
while slow != fast:
fast = sumSquares(sumSquares(fast))
slow = sumSquares(slow)
return fast == 1