数字以0123456789101112131415…的格式序列化到一个字符序列中。在这个序列中,第5位(从下标0开始计数)是5,第13位是1,第19位是4,等等。
请写一个函数,求任意第n位对应的数字。
示例 1:
输入:n = 3
输出:3
示例 2:
输入:n = 11
输出:0
限制:
0 <= n < 2^31
注意:本题与主站 400 题相同:https://leetcode-cn.com/problems/nth-digit/
class Solution {
public:
int findNthDigit(int n) {
int range[] = { 0, 0, 10, 190, 2890, 38890, 488890, 5888890, 68888890, 788888890 };
int i;
for (i = 1; i <= 9; ++i)
{
if (range[i] > n)
break;
}
i -= 1;
n -= range[i];
if (i == 1)
return nthDigit(n / i, n % i);
else
return nthDigit((int)pow(10, i - 1) + n / i, n % i);
}
int nthDigit(int x, int n) {
string s = to_string(x);
return s[n] - '0';
}
};