|
| 1 | +# 2081. Sum of k-Mirror Numbers |
| 2 | +A **k-mirror number** is a **positive** integer **without leading zeros** that reads the same both forward and backward in base-10 **as well as** in base-k. |
| 3 | + |
| 4 | +* For example, `9` is a 2-mirror number. The representation of `9` in base-10 and base-2 are `9` and `1001` respectively, which read the same both forward and backward. |
| 5 | +* On the contrary, `4` is not a 2-mirror number. The representation of `4` in base-2 is `100`, which does not read the same both forward and backward. |
| 6 | + |
| 7 | +Given the base `k` and the number `n`, return *the **sum** of the* `n` ***smallest** k-mirror numbers*. |
| 8 | + |
| 9 | +#### Example 1: |
| 10 | +<pre> |
| 11 | +<strong>Input:</strong> k = 2, n = 5 |
| 12 | +<strong>Output:</strong> 25 |
| 13 | +<strong>Explanation:</strong> |
| 14 | +The 5 smallest 2-mirror numbers and their representations in base-2 are listed as follows: |
| 15 | + base-10 base-2 |
| 16 | + 1 1 |
| 17 | + 3 11 |
| 18 | + 5 101 |
| 19 | + 7 111 |
| 20 | + 9 1001 |
| 21 | +Their sum = 1 + 3 + 5 + 7 + 9 = 25. |
| 22 | +</pre> |
| 23 | + |
| 24 | +#### Example 2: |
| 25 | +<pre> |
| 26 | +<strong>Input:</strong> k = 3, n = 7 |
| 27 | +<strong>Output:</strong> 499 |
| 28 | +<strong>Explanation:</strong> |
| 29 | +The 7 smallest 3-mirror numbers are and their representations in base-3 are listed as follows: |
| 30 | + base-10 base-3 |
| 31 | + 1 1 |
| 32 | + 2 2 |
| 33 | + 4 11 |
| 34 | + 8 22 |
| 35 | + 121 11111 |
| 36 | + 151 12121 |
| 37 | + 212 21212 |
| 38 | +Their sum = 1 + 2 + 4 + 8 + 121 + 151 + 212 = 499. |
| 39 | +</pre> |
| 40 | + |
| 41 | +#### Example 3: |
| 42 | +<pre> |
| 43 | +<strong>Input:</strong> k = 7, n = 17 |
| 44 | +<strong>Output:</strong> 20379000 |
| 45 | +<strong>Explanation:</strong> The 17 smallest 7-mirror numbers are: |
| 46 | +1, 2, 3, 4, 5, 6, 8, 121, 171, 242, 292, 16561, 65656, 2137312, 4602064, 6597956, 6958596 |
| 47 | +</pre> |
| 48 | + |
| 49 | +#### Constraints: |
| 50 | +* `2 <= k <= 9` |
| 51 | +* `1 <= n <= 30` |
| 52 | + |
| 53 | +## Solutions (Python) |
| 54 | + |
| 55 | +### 1. Solution |
| 56 | +```Python |
| 57 | +class Solution: |
| 58 | + def kMirror(self, k: int, n: int) -> int: |
| 59 | + x = 1 |
| 60 | + nums = [] |
| 61 | + |
| 62 | + while True: |
| 63 | + for a in range(x, 10 * x): |
| 64 | + b = c = int(str(a) + str(a)[-2::-1]) |
| 65 | + d = '' |
| 66 | + while c > 0: |
| 67 | + d = str(c % k) + d |
| 68 | + c //= k |
| 69 | + if d == d[::-1]: |
| 70 | + nums.append(b) |
| 71 | + if len(nums) == n: |
| 72 | + return sum(nums) |
| 73 | + for a in range(x, 10 * x): |
| 74 | + b = c = int(str(a) + str(a)[::-1]) |
| 75 | + d = '' |
| 76 | + while c > 0: |
| 77 | + d = str(c % k) + d |
| 78 | + c //= k |
| 79 | + if str(d) == str(d)[::-1]: |
| 80 | + nums.append(b) |
| 81 | + if len(nums) == n: |
| 82 | + return sum(nums) |
| 83 | + |
| 84 | + x *= 10 |
| 85 | +``` |
0 commit comments