剑指 Offer 44. 数字序列中某一位的数字
思路:迭代+求整/求余
- 确定n所在数字的位数
- 确定n所在的数字
- 确定n是num的哪个数位
1.确定n所在数字的位数
循环执行n减去一位数,二位数,…的数位count,直到n<=count跳出。
2.确定所求数位所在的数字
n u m = s t a r t + ( n − 1 ) / / d i g i t num=start+(n-1)//digit num=start+(n−1)//digit
3.确定所求num的哪一数位
s=str(num)
res=s[(n-1)%digit]-'0';
class Solution {
public:
int findNthDigit(int n) {
int digit=1;
long start=1;
long count=9*digit*start;
while(n>count){
n-=count;
digit++;
start*=10;
count=long(9)*digit*start;
}
int num=start+(n-1)/digit;
int res=to_string(num)[(n-1)%digit]-'0';
return res;
}
};
时间复杂度 O(logn)
空间复杂度 O(logn) 将数字转化为字符串,占用O(logn)额外空间