400. 第 N 位数字
难度中等294
给你一个整数 n ,请你在无限的整数序列 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …] 中找出并返回第 n 位上的数字。
示例 1:
输入:n = 3输出:3
示例 2:
输入:n = 11输出:0解释:第 11 位数字在序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... 里是 0 ,它是 10 的一部分。
提示:
- 1 <= n <= 231 - 1
思路
- 模拟+找规律
代码
class Solution {
public:
int findNthDigit(int n) {
/*
1-9 10-99 100-999 1000-9999 10000-99999
9 90*2 900*3 9000*4
*/
int s=9,temp,i=1,count=9,flag=0;
if(n<=s)
return n;
while(s<n)//从两位数:10开始
{
i++;
temp=pow(10,i-1);
if(temp<1e8)//防止越界
temp=9*temp*i;
else
flag=1;
if( flag==1||(n>=s&&n-s<=temp) )
{
int x=(n-s+1)/i;//这段第几个数字
int y=(i-1)-(n-s-1)%i;//第几位
x+=count;//数字x
i=x%10;//余数
while(y-->=0)
{
i=x%10;
x=x/10;//倒序
}
return i;
}
s+=temp;
count+=9*pow(10,i-1);//第几阶段
}
return 0;
}
};