class Solution:
def newInteger(self, n: int) -> int:
# Convert n to base 9 and interpret as decimal
res = 0
base = 1
while n > 0:
res += (n % 9) * base
n //= 9
base *= 10
return res
class Solution {
public:
int newInteger(int n) {
int res = 0, base = 1;
while (n > 0) {
res += (n % 9) * base;
n /= 9;
base *= 10;
}
return res;
}
};
class Solution {
public int newInteger(int n) {
int res = 0, base = 1;
while (n > 0) {
res += (n % 9) * base;
n /= 9;
base *= 10;
}
return res;
}
}
var newInteger = function(n) {
let res = 0, base = 1;
while (n > 0) {
res += (n % 9) * base;
n = Math.floor(n / 9);
base *= 10;
}
return res;
};
The "Remove 9" problem asks you to find the n
th positive integer that does not contain the digit '9' in its decimal representation. For example, if n = 9
, the answer is 10 (since 9 is skipped).
n
, return the n
th integer in the sequence of positive numbers that do not have the digit '9'.n
.
At first glance, you might think to simply iterate from 1 upwards, skipping numbers containing '9', until you reach the n
th valid number. While this brute-force method works for small n
, it's inefficient for large values.
To optimize, it's helpful to notice a pattern: the sequence of numbers without any '9' digits is like counting in base 9. For example, the numbers 1, 2, ..., 8, 10, 11, ... (skipping 9, 19, 29, etc.) correspond to numbers written in base 9, but interpreted as decimal.
Recognizing this allows us to convert n
directly to its base-9 representation and interpret that as the answer.
n
to its base-9 representation. For example, if n = 10
, the base-9 representation is "11".
n = 10
, base-9 "11" is decimal 11.
n
.
We use a loop to convert n
to base 9 by repeatedly taking n % 9
for the current digit, then dividing n
by 9 to process the next digit. We build the result as a decimal number by multiplying each digit by the appropriate power of 10.
Let's walk through an example with n = 15
:
This process works for any value of n
, efficiently skipping all numbers with the digit '9'.
n
because it checks every number up to the answer.n
.n
.
The "Remove 9" problem is elegantly solved by recognizing the pattern between numbers without the digit '9' and base-9 counting. Instead of brute-force filtering, we convert n
to base-9 and interpret the result as a decimal number. This provides a fast, simple, and scalable solution that avoids unnecessary computation and leverages number system insights.