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 nth
(1-indexed) integer in the new sequence.
Example 1:
Input: n = 9 Output: 10
Example 2:
Input: n = 10 Output: 11
思路:
这道题让我们移除所有包含数字9的数字,然后得到一个新的数列,给了一个数字n,求在这个新的数组中第n个数字。多写些数字来看看:
0,1,2,3,4,5,6,7,8 (移除了9)
10,11,12,13,14,15,16,17,18 (移除了19)
.....
80,81,82,83,84,85,86,87,88 (移除了89)
(移除了 90 - 99 )
100,101,102,103,104,105,106,107,108 (移除了109)
可以发现,8的下一位就是10了,18的下一位是20,88的下一位是100,实际上这就是九进制的数字的规律,那么这道题就变成了将十进制数n转为九进制数,这个就没啥难度了,就每次对9取余,然后乘以 base,n每次自除以9,base 每次扩大10倍,参见代码如下:
class Solution {
public int newInteger(int n) {
int res = 0; int base = 1;
while(n > 0) {
res += n % 9 * base;
n = n / 9;
base *= 10;
}
return res;
}
}