-
-
Notifications
You must be signed in to change notification settings - Fork 46.6k
/
Copy pathsol1.py
58 lines (49 loc) · 1.55 KB
/
sol1.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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"""
Project Euler problem 145: https://projecteuler.net/problem=145
Author: Vineet Rao
Problem statement:
Some positive integers n have the property that the sum [ n + reverse(n) ]
consists entirely of odd (decimal) digits.
For instance, 36 + 63 = 99 and 409 + 904 = 1313.
We will call such numbers reversible; so 36, 63, 409, and 904 are reversible.
Leading zeroes are not allowed in either n or reverse(n).
There are 120 reversible numbers below one-thousand.
How many reversible numbers are there below one-billion (10^9)?
"""
def odd_digits(num: int) -> bool:
"""
Check if the number passed as argument has only odd digits.
>>> odd_digits(123)
False
>>> odd_digits(135797531)
True
"""
while num > 0:
digit = num % 10
if digit % 2 == 0:
return False
num //= 10
return True
def solution(max_num: int = 1_000_000_000) -> int:
"""
To evaluate the solution, use solution()
>>> solution(1000)
120
>>> solution(1_000_000)
18720
>>> solution(10_000_000)
68720
"""
result = 0
# All single digit numbers reverse to themselves, so their sums are even
# Therefore at least one digit in their sum is even
# Last digit cannot be 0, else it causes leading zeros in reverse
for num in range(11, max_num):
if num % 10 == 0:
continue
num_sum = num + int(str(num)[::-1])
num_is_reversible = odd_digits(num_sum)
result += 1 if num_is_reversible else 0
return result
if __name__ == "__main__":
print(f"{solution() = }")