此题是求从1开始的正整数序列中的第n个数字
1,2,3,4,5,6,7,8,9,1 0,11,12…
第十一个数字是0
思路:
从1-9共有9个数字,基础数值为 0 ,每一位数字占有 1位
从10-99共有90个数字,基础数值为 9 ,每一位数字占有 2位
从100-999共有900各数字 99 ,每一位数字占有 3位
…
计算n处于哪一个区间,在根据基础数值加上剩余的数字位数即可得到最后一个数字,如果刚好整除,返回最后一位,否则返回相应位数的数字。
比如,第289个数字,(9+90x2)<289<(9+90x2+900x3),所以应该在99的基础上加上(289-189)/3=33,因为(289-189)%3=1不等于0,99+33+1=133
因为余数是1,返回133中的第一位 1
class Solution {
public:
int findNthDigit(int n) {
int base=1;
int countbase=9;
if(n<10)
return n;
int floor=1;
int total=0;
int total_save;
bool over=false;
while(total<n)
{
int rate=INT_MAX/(1.0*countbase)/(1.0*floor);
if(rate<1)
{
over=true;
break;
}
total+=countbase*floor;
if(total<n)
total_save=total;
floor++;
base*=10;
countbase*=10;
}
//计算具体是哪个数字
if(!over)
{
floor--;
base/=10;
countbase/=10;
}
int left=n-total_save;
int index=left/floor;
int yu=left%floor;
int num;
if(yu==0)
{
num=base-1+index;
return num%10;
}
else
num=base-1+index+1;
int result;
for(int i=0;i<floor-yu+1;i++)
{
result=num%10;
num/=10;
}
return result;
}
};