天天看点

【C语言】 LeetCode 400. Nth Digit题目:解答:

题目:

Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...

Note:

n is positive and will fit within the range of a 32-bit signed integer (n < 231).

Example 1:

Input:
3

Output:
3
      

Example 2:

Input:
11

Output:
0

Explanation:
The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.      

解答:

//以10的n次方作为分界线,计算之前所有数字的总个数,与n值比较,确定所求结果所在范围,然后再确定所求结果所在数值,得出结果
int findNthDigit(int n) {
    int flag=1;
    int multi=1;
    long sum=9;
    int mod;
    long num;
    if(n<10) return n;
    while(sum<n)
    {
        flag++;
        multi=multi*10;
        if(flag==9)break;//sum 为int类型,防止sum超出存储范围
        sum=sum+flag*(multi*10-multi);
    }
    if(flag==9)
    {
        mod=(n-sum)%flag;
    }
    else
    {
        sum=(sum-flag*(multi*10-multi));
        mod=(n-sum)%flag;
    }
    
    if(mod==0)
    {
        num=(n-sum)/flag+multi-1;
        num=num%10;
    }
    else
    {
        num=(n-sum)/flag+multi;
        num=num/pow(10,flag-mod);
        num=num%10;
    }
    return num;
        
}