1.题目
Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …
有这样一个无限序列,求这个序列的第n个数字是多少。
Note:
n is positive and will fit within the range of a 32-bit signed integer (n < 231).
2.分析
第一步,确定第n个数字所在的number是多少。也就是从1开始数,累积每个数的位数,直到和大于等于n。
1-9 每个数长度为1 总长 9*1
10-99 每个数长度为2 总长 90*2
100-999 每个数长度为3 总长900*3
。。。
9*pow(10,i-1)*i
第二步,确定n在number的哪一位上。
3.代码
class Solution {
public:
int findNthDigit(int n) {
if (n < 10)
return n;
long long sum = 0;
int i = 1;
while (n > sum) {
sum += 9 * i*pow(10, i - 1);
++i;
}
i -= 1;
int remain = n - (sum - 9 * i*pow(10, i - 1));
int number = pow(10, i - 1) + (remain - 1) / i;//找出所在的数
int c = remain%i == 0 ? 0 : i - remain%i;//所在的位
while (c) {
number = number / 10;
--c;
}
return number % 10;
}
};