|
| 1 | +""" |
| 2 | +Problem 145: https://projecteuler.net/problem=145 |
| 3 | +
|
| 4 | +Name: How many reversible numbers are there below one-billion? |
| 5 | +
|
| 6 | +Some positive integers n have the property that the |
| 7 | +sum [ n + reverse(n) ] consists entirely of odd (decimal) digits. |
| 8 | +For instance, 36 + 63 = 99 and 409 + 904 = 1313. |
| 9 | +We will call such numbers reversible; so 36, 63, 409, and 904 are reversible. |
| 10 | +Leading zeroes are not allowed in either n or reverse(n). |
| 11 | +
|
| 12 | +There are 120 reversible numbers below one-thousand. |
| 13 | +
|
| 14 | +How many reversible numbers are there below one-billion (10^9)? |
| 15 | +
|
| 16 | +
|
| 17 | +Solution: |
| 18 | +
|
| 19 | +Here a brute force solution is used to find and count the reversible numbers. |
| 20 | +
|
| 21 | +""" |
| 22 | +from __future__ import annotations |
| 23 | + |
| 24 | + |
| 25 | +def check_if_odd(sum: int = 36) -> int: |
| 26 | + """ |
| 27 | + Check if the last digit in the sum is even or odd. If even return 0. |
| 28 | + If odd then floor division by 10 is used to remove the last number. |
| 29 | + Process continues until sum becomes 0 because no more numbers. |
| 30 | + >>> check_if_odd(36) |
| 31 | + 0 |
| 32 | + >>> check_if_odd(33) |
| 33 | + 1 |
| 34 | + """ |
| 35 | + while sum > 0: |
| 36 | + if (sum % 10) % 2 == 0: |
| 37 | + return 0 |
| 38 | + sum = sum // 10 |
| 39 | + return 1 |
| 40 | + |
| 41 | + |
| 42 | +def find_reverse_number(number: int = 36) -> int: |
| 43 | + """ |
| 44 | + Reverses the given number. Does not work with number that end in zero. |
| 45 | + >>> find_reverse_number(36) |
| 46 | + 63 |
| 47 | + >>> find_reverse_number(409) |
| 48 | + 904 |
| 49 | + """ |
| 50 | + reverse = 0 |
| 51 | + |
| 52 | + while number > 0: |
| 53 | + temp = number % 10 |
| 54 | + reverse = reverse * 10 + temp |
| 55 | + number = number // 10 |
| 56 | + |
| 57 | + return reverse |
| 58 | + |
| 59 | + |
| 60 | +def solution(number: int = 1000000000) -> int: |
| 61 | + """ |
| 62 | + Loops over the range of numbers. |
| 63 | + Checks if they have ending zeros which disqualifies them from being reversible. |
| 64 | + If that condition is passed it generates the reversed number. |
| 65 | + Then sum up n and reverse(n). |
| 66 | + Then check if all the numbers in the sum are odd. If true add to the answer. |
| 67 | + >>> solution(1000000000) |
| 68 | + 608720 |
| 69 | + >>> solution(1000000) |
| 70 | + 18720 |
| 71 | + >>> solution(1000000) |
| 72 | + 18720 |
| 73 | + >>> solution(1000) |
| 74 | + 120 |
| 75 | + """ |
| 76 | + answer = 0 |
| 77 | + for x in range(1, number): |
| 78 | + if x % 10 != 0: |
| 79 | + reversed_number = find_reverse_number(x) |
| 80 | + sum = x + reversed_number |
| 81 | + answer += check_if_odd(sum) |
| 82 | + |
| 83 | + return answer |
| 84 | + |
| 85 | + |
| 86 | +if __name__ == "__main__": |
| 87 | + print(f"{solution() = }") |
0 commit comments