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;
}
};