Topic describes

Ideas for solving problems (Mathematical laws)

  • In my opinion, the core of the problem is to understand how to split a string into intervals of different digits.
  1. First, determine which interval n is in. The interval is divided into 1-9, 10-99, 100-999…
  2. Compute which subscript n is in the current interval
  3. Find the real number that corresponds to the n subscript
  4. Figure out which digit of the real number is what we’re going to return

The formula


n The actual number of the subscript = Interval starting value + (Interval number 1 ) / Number of intervals N The true number of the subscript = the start value of the interval + (interval number -1)/interval number -1

Which digit of the real number = (Interval number 1 ) % What interval is mod Which digit of the real number = (interval -1) \% interval mod

The problem solving code

var findNthDigit = function(n) {
    // where n is the subscript
    // If the subscript is less than 10, return n
    if (n < 10) {
        return n;
    }
    // If n is greater than or equal to 10, we need to determine which interval n is in
    let numInterval = 0;
    for (let i = 1; i < 100; i++) {
        if ((n - 9) < 9 * Math.pow(10,i) * (i+1)) {
            numInterval = i+1;
            break; }}// Calculate the index n in the current range
    for (let i = 0; i < numInterval-1; i++) {
        n = n - 9 * (10 ** i) * (i+1);
    }
    // The actual number of the subscript that n points to = the start value of the interval + (interval number -1)/interval number
    const trueNum = 10 ** (numInterval - 1) + parseInt( (n - 1) / numInterval )
    // The actual number may be a multi-digit number, but it is required to return the number that the subscript refers to, so the number that the subscript refers to is
    // (interval 1) % interval 1
    const numIndex = (n - 1) % numInterval;
    return String(trueNum)[numIndex]
};
Copy the code

Conclusion (this topic gives us the enlightenment of thinking)

  • Lesson: Learn to solve problems through mathematical laws