题目:
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: 9 Output: 10
Hint: n will not exceed 9 x 10^8.
思路:
我们首先找规律,移除含有9的数字之后:
8后面的数成了10,
18后面的数成了20,
……
88后面的数成了100.
而这刚好就是9进制数的特点:每次遇到9就进位。如果我们把n转换为就进制n’,然后把n'当做十进制输出出来,就是所求的结果。妙不妙?
注意这里仅仅局限于移除9的情况。如果需要移除8或者7就不能这样了。假如需要移除7,如果转换为7进制,则把含有8,9的数也会错误地移除掉。如果遇到其它数字,就需要设计更通用的方法了,好像挺复杂的。
这个算法的时间复杂度是O(logn),空间复杂度是O(1)。
代码:
class Solution {
public:
int newInteger(int n) {
int ans = 0;
int base = 1;
while(n != 0) {
ans = (n % 9) * base + ans;
n /= 9;
base *= 10;
}
return ans;
}
};
这篇博客介绍了LeetCode上的第660题,题目要求从1开始移除所有包含9的整数,然后找出序列中的第n个数。作者发现,移除9后的新序列与9进制数对应,因此通过将n转化为9进制再转换回十进制即可找到答案。文章分析了问题的思路,时间复杂度和空间复杂度,并给出了具体的解题代码。
310

被折叠的 条评论
为什么被折叠?



