LeetCode刷题笔记--400. Nth Digit

400. Nth Digit

400. Nth Digit

Easy

228705FavoriteShare

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.

这道题需要先找规律,然后按照规律来算,特别需要注意当p正好等于0的时候比较特殊,需要特殊处理。等于0的情况我在vs里调过的。

class Solution {
public:
    int findNthDigit(int n) {
        //先找一下规律:
        //1位的情况,从1~9,总共9个数字
        //2位的情况,从10~99,总共90*2个数字
        //3位的情况,从100~999,总共900*3个数字
        //n位的情况,从10^(n-1)~10^(n)-1,总共有9*10^(n-1)*n个数字
        if(n<10)return n;
        int b=1;//用来记录在上述哪段范围内
        int ans=0;
        int ans1=0;
        long temp=n;
        //long temp1;
        while(temp>(9*pow(10,b-1)*b))
        {
            temp-=9*pow(10,b-1)*b;
            b++;
        }
        
        int p=temp%b;//余的位数
        ans=pow(10,b-1)+temp/b;
        int t=b-p+1;
        if(p==0)
        {
            ans--;
            t=1;
        }
        for(int i=0;i<t;i++)
        {
            ans1=ans%10;
            ans/=10;
        }
        return ans1;
    }
};

猜你喜欢

转载自blog.csdn.net/vivian0239/article/details/87968566