剑指 Offer 44. 数字序列中某一位的数字 - 力扣(LeetCode)
LeetCode第 400 题:第N个数字(C++)_zj-CSDN博客,一样的
class Solution {
public:
int findNthDigit(int n) {
//digit表示位数
long base = 9, digit = 1;
while(n > base*digit){
n -= base*digit;
base *= 10;
++digit;
}
//n对应的数字是digit位数
//n现在表示digits位数的第n个数字
int num = pow(10, digit-1);//最小的digit位数
int x = n / digit, y = n % digit;
if(y) num += x;//digit位数是从000...开始的
else num += x-1;//y == 0,n指向的数字是第x个数的末尾位
//cout << num << endl;
if(y == 0) y = digit;
return to_string(num)[y-1] - '0';//字符串下标从0开始
}
};