又是一道找规律的题目,头大得很。
为了方便10 - n 位的规律,我们默认n >= 10,其他情况只要renturn n; 就可以了。
0-9 1 10
10-99 2 90 180
100-999 3 900 2700
1000-9999 4 9000 36000
通过逐个排除,我们可以确定要找的数字所在区间,例如第1001个数字。
1001 - 10 = 991
991 - 90 = 811
811 < 2700
因此第1001个数字在,100-999之间,因为该区间内每个数字占3位,所以可以得到该数字。
例如:811 = 270 * 3 + 1;
所以,第1001个数字位7
class Solution {
public:
int findNthDigit(int n) {
if(n <= 9){
return n;
}
n -= 10;
long long count = 90;
long long digit = 2;
long long sum = 180;
while(n > sum){
n -= sum;
digit++;
count *= 10;
sum = digit * count;
}
int num = pow(10,digit-1) + n/digit;
int indexFromRight = digit - n%digit;
for(int i = 1;i < indexFromRight; i++){
num /= 10;
}
return num%10;
}
};
本文介绍了一种高效算法,用于找到一个无限长的数字序列中的第N位数字。通过对数字区间的逐级筛选,算法能快速定位目标数字,并通过数学运算提取出具体数值。适用于竞赛编程和算法优化场景。
395

被折叠的 条评论
为什么被折叠?



