题目描述:
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.
根据位数不同进行讨论,一位数有9个,二位数有90个,三位数有900个,这样可以不断递推,确定序列中第n位数落在哪个数、哪一位上。
class Solution {
public:
int findNthDigit(int n) {
long long count=9;
long long start=1;
long long digit=1;
while(n>count*digit)
{
n-=count*digit;
start+=count;
digit++;
count*=10;
}
long long num=start+(n-1)/digit;
string s=to_string(num);
return s[(n-1)%digit]-'0';
}
};