[LeetCode 660] Remove 9
Start from integer 1, remove any integer that contains 9 such as 9, 19, 29...
So now, you will have a new integer sequence: 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, ...
Given a positive integer n
, you need to return the n-th integer after removing. Note that 1 will be the first integer.
Example 1:
Input: n = 9
Output: 10
Constraints:
1 <= n <= 8 x 10^8
Given the constraints, it is obvious that a brute force solution will get TLE.
Solution 1. Solve smaller subproblems of fixed digits' count first.
1. removeCnt[digitCnt] = removeCnt[digitCnt - 1] * 8 + 10^(digitCnt - 1); Using this formula we can get an accumulation array[i] that stores the remove count of all numbers whose digit count is <= i.
2. When the removed count plus n <= total number count at digit count i, we know the answer must be an integer of digit count i.
3. subtract remaining count of all fewer digit counts, denote the new count as M, now we need to find the Mth number starting from the very first number of digit count i.
The runtime and space are O(logN). Here we use long to avoid integer overflow!
class Solution { public int newInteger(int n) { long p = 1, N = n; int digitCnt = 1; long[] rmCnt = new long[11]; for(; digitCnt <= 10; digitCnt++) { rmCnt[digitCnt] = rmCnt[digitCnt - 1] * 9 + p; p *= 10; if(p - 1 - rmCnt[digitCnt] >= N) { break; } } p /= 10; long fewerDigitsRemainCnt = p - 1 - rmCnt[digitCnt - 1]; N -= (fewerDigitsRemainCnt + 1); long v = p; while(N > 0) { long d = N / (p - rmCnt[digitCnt - 1]); long mod = N % (p - rmCnt[digitCnt - 1]); N -= d * (p - rmCnt[digitCnt - 1]); v += d * p; p /= 10; digitCnt--; } return (int)v; } }
Solution 2.
Solution is really badass but a bit complicated to implement, there is an much easier solution. By removing 9, we changed the 10-based system to 9-based. So the set of numbers without 9 is the same with the set of base-9 numbers, and they occur in the same order. So the answer is just the nth base-9 number. We convert the nth 9-based number back to its 10-based representation and that is our answer.
class Solution { public int newInteger(int n) { return Integer.parseInt(Integer.toString(n, 9)); } }
class Solution { public int newInteger(int n) { int ans = 0, base = 1; while(n > 0) { int mod = n % 9; ans += mod * base; n /= 9; base *= 10; } return ans; } }