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 < 2^31).

Example 1:

Input: 3
Output: 3

Example 1:

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.

Solution:

class Solution {
public:
    int findNthDigit(int n) {
        if(n <= 9) return n;
        int s=1,i=1,j=9,base=0;
        while(n>j && s<8){
            s++;
            i*=10;
            j=j+s*i*9;
        }
        if(s == 8 && n > j){
            s++;
            i*=10;
            base = j;
        }else{
            base = j - s * i * 9;
        }
        int offset = n - base - 1;
        int target = i + offset / s;
        int index = offset % s;
        return to_string(target)[index] - '0';
    }
};

你可能感兴趣的:(400. Nth Digit)