一位数: 1-9,共9个数字
两位数:10 - 99 共 90个数, 2* 90个数字
三位数:100-999, 共900个数,3 * 900 个数字
四位数:1000-9999,共9000个数字, 4 * 90000个数字
因此,第一步,是确定第n个数字几位数,确定的方法是不断减去cnt * base
确定完了是第几个数字,在确定这个数字属于哪个数。
然后再找到这个数字是第几位数,然后将那一个数字取出。
class Solution {
public:
int findNthDigit(int n) {
int d = 1, count = 9;
while (n > (long) d * count) {
n -= d * count;
d++;
count *= 10;
}
int index = n - 1;
int start = (int) pow(10, d - 1); // 起点是几位数
int num = start + index / d; // 找到对应的数
int digitIndex = index % d; // 找到对应位置
int digit = (num / (int) (pow(10, d - digitIndex - 1))) % 10; // 找到该数对应的位。
return digit;
}
};