• Requirements: Numbers 0123456789101112131415… Serialized to a character sequence. In this sequence, bit 5 (counting from subscript 0) is 5, bit 13 is 1, bit 19 is 4, and so on.
  • For example, input n=3, output 3; Input n=11, output 0.
  • Ideas:
  1. Each digit in 101112 is called a digit, or the NTH bit;
  2. 10,11, and 12 are called num;
  3. Digit represents the number of digits. 1 is 1,15 is 2,103 is 3.
  4. Start represents the starting digit of a digit. 1 digit is 0,2 digit is 10,3 digit is 100…
Digital range digits Digital number Digital number
1 ~ 9 1 9 9
10 to 99 2 90 180
100 ~ 999 3 900 2700
. . . .
start~end digit 9 x start * start * 9 digit

Digit recursive formula digit = digit + 1

Starting number recursion formula start = start × 10

Count = 9 × start × digit

  • Steps:
  1. Determine the number of digits of n, denoted as digit;

    Loop n minus one digit, two digit… Until n < = count

  2. Determine the number of n, denoted as num;

    Digit = start + (n-1)/digit; digit = start + (n-1)/digit; digit = start + (n-1)/digit

  3. Determine which digit in num n is, and return the result.

    The desired digit is the (n-1)%digit of num, starting with the 0th digit. s=str(num); res = int(s[(n-1)%digit]); The (n-1) % digit representing num and converted to int

  • Note: n -= count; And n = n – count; The output is not quite the same. The first one works, the second one won’t compile even with casts, and it’s not clear what the problem is.

  • Code:
class Solution {
    public int findNthDigit(int n) {
        long digit = 1;
        long start = 1;
        long count = 9;
        long m = (long) n;
        while (m > count) { / / 1.
            m = m - count;
            digit++;
            start *= 10;
            count = digit * start * 9;
        }
        long num = start + (m - 1) / digit; / / 2.
        return (int)Long.toString(num).charAt((m - 1) % digit) - '0'; / / 3.}}Copy the code