Finding nth digit of natural numbers sequence in JavaScript


Natural Number Sequence:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12...

This sequence extended infinitely is known as natural number sequence.

We are required to write a JavaScript function that takes in a number, num, as the first and the only argument. The function should find and return the (num)th digit that will appear in this sequence when written, removing the commas and whitespaces.

For example −

If the input number is −

const num = 13;

Then the output should be −

const output = 1;

because '1234567891011' this string has its 13th number as 1

Example

The code for this will be −

 Live Demo

const num = 13;
const findDigit = (num = 1) => {
   let str = '';
   let i = 1;
   while(str.length < num){
      str += i;
      i++;
   };
   const required = str[num - 1];
   return required;
};
console.log(findDigit(num));

Output

And the output in the console will be −

1

Updated on: 03-Mar-2021

415 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements