Finding the nth digit of natural numbers JavaScript


We know that natural numbers in Mathematics are the numbers starting from 1 and spanning infinitely.

First 15 natural numbers are −

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Therefore, the first natural digit is 1, second is 2, third is 3 and so on. But when we exceed 9, then tenth natural digit is the first digit of 10 i.e., 1 and 11th natural digit is the next i.e., 0.

We are required to write a JavaScript function that takes in a number, say n, and finds and returns the nth natural digit.

Example

const findNthDigit = (num = 1) => {
   let start = 1;
   let len = 1;
   let count = 9;
   while(num > len * count) {
      num -= len * count;
      len++; count *= 10;
      start *= 10;
   };
   start += Math.floor((num-1)/len);
   let s = String(start);
   return Number(s[(num-1) % len]);
};
console.log(findNthDigit(5));
console.log(findNthDigit(15));
console.log(findNthDigit(11));
console.log(findNthDigit(67));

Output

And the output in the console will be −

5
2
0
8

Updated on: 23-Nov-2020

261 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements