c++ simple solution


  • 0

    We need to consider ranges like:

    • 1 - 9 numbers with 1 digit;
    • 10 - 99 numbers with 2 digits;
    • 100 - 999 numbers with 3 digits etc.

    Thus, we will find the start of the range.
    Since we know the start, quantity of digits in a numbers in this range and a index of our digit we easily can find the number (that contains this digit), and the index of digit in this number.

    int findNthDigit(int n) {
        long long end = 9, start = 1, num_sz = 1;
        if (n <= end) return n;
        // looking for a range that contains the number, and start of this range
        while (n > end) {
            n -= end;
            start *= 10;
            num_sz++;
            end = 9 * start * num_sz;
        }
        // index of the digit in the number
        int index = (n % num_sz == 0) ? 0 : num_sz - n % num_sz;
        // the number   
        int num = start + n / num_sz - (n % num_sz == 0 ? 1 : 0);
        // shift to the digit
        while (index--) num /= 10;
        return num % 10;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.