Remove 9 Problem
Description
LeetCode Problem 660.
Start from integer 1, remove any integer that contains 9 such as 9, 19, 29...
Now, you will have a new integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 10, 11, ...].
Given an integer n, return the n^th (1-indexed) integer in the new sequence.
Example 1:
Input: n = 9
Output: 10
Example 2:
Input: n = 10
Output: 11
Constraints:
1 <= n <= 8 * 10^8
Solution
Approach: Base 9
The numbers that survive are exactly the numbers whose decimal digits are all in 0–8. Listed in order, they look just like counting in base 9: 1, 2, ..., 8, 10, 11, ..., 18, 20, .... Base 9 counts with the digits 0–8 in the same order, so the n-th surviving number is n written in base 9, read as a decimal number.
Convert by repeatedly taking n % 9 as the next digit (from the lowest place up) and dividing n by 9, placing each digit at the next power of ten. For example n = 9 is 10 in base 9, and n = 81 is 100.
This is far faster than counting up and skipping numbers: n can be 8 * 10^8. The answer for the largest n is 2052305618, which still fits in a 32-bit integer.
Complexity: O(log n) time and O(1) extra space.
class Solution:
def newInteger(self, n: int) -> int:
# The numbers without a 9 are exactly the base-9 numerals: write n in base 9
# and read the digits as a decimal number.
ans, place = 0, 1
while n > 0:
ans += n % 9 * place
n //= 9
place *= 10
return ans