题目:
Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...
Note:
n is positive and will fit within the range of a 32-bit signed integer (n < 231).
Example 1:
Input: 3 Output: 3
Example 2:
Input: 11 Output: 0 Explanation: The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.
思路:
可以分为三步来计算:1)找出给定的n落在几位数的范围内;2)找出具体落在哪个数字上;3)找出具体在哪一位上。
一位数一共有9个,两位数一共有90个,三位数一共有900个,以此类推,因此可以每增加一位数字,看n是否在这个范围之内。我们以n = 150为例来具体说明:1)首先一位数有9个数字并且9 < 150,所以位数可以加1,这样 n - 9 = 141,然后两位数的数字有2 * 90 = 180位,大于141,所以目标数字肯定是在两位数上。2)求具体数字,可以用10 + (141 - 1) / 2 = 80求出。3)最后求具体落在哪一位上,可以用(141 - 1) % 2 = 0求出为第0位,即8。思路挺直观,可是要写出bug free的代码却不是那么容易。
代码:
class Solution {
public:
int findNthDigit(int n) {
long digit = 1, ith = 1, base = 9;
while(n > base * digit) {
n -= base * digit;
++digit;
ith += base; // the accumulated number
base *= 10;
}
string s = to_string(ith + (n - 1)/digit);
return s[(n - 1) % digit] - '0';
}
};
这篇博客介绍了LeetCode第400题——如何找到无限整数序列的第n位数字。文章通过举例和分步解释思路,展示了如何确定n所在的位数范围、具体数字及所在位置,并分享了实现算法时可能遇到的挑战。

897

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



