Skip to content

Commit ea09be9

Browse files
committed
feat: add happy number
1 parent e2b68d2 commit ea09be9

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

arrays_and_strings/happy_number/__init__.py

Whitespace-only changes.
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
def happy_number(n: int) -> bool:
2+
slow = n
3+
fast = squared_digits_sum(n)
4+
5+
while fast != slow or n != 1:
6+
slow = squared_digits_sum(slow)
7+
fast = squared_digits_sum(squared_digits_sum(fast))
8+
9+
if fast == slow:
10+
return False
11+
return True
12+
13+
def squared_digits_sum(n: int) -> int:
14+
digits_sum = 0
15+
while n > 0:
16+
n, digit = divmod(n,10)
17+
digits_squared = digit * digit
18+
digits_sum += digits_squared
19+
return digits_sum

0 commit comments

Comments
 (0)