Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

หาตัวเลขลำดับที่ n ของจำนวนธรรมชาติใน JavaScript

เรารู้ว่าจำนวนธรรมชาติในคณิตศาสตร์คือตัวเลขเริ่มจาก 1 และไปจนถึงอนันต์

จำนวนธรรมชาติ 15 ตัวแรกคือ:

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

ดังนั้น ตัวเลขธรรมชาติลำดับที่ 1 คือ 1 ลำดับที่ 2 คือ 2 ลำดับที่ 3 คือ 3 และต่อไป แต่เมื่อเกิน 9 แล้ว ตัวเลขธรรมชาติลำดับที่ 10 คือตัวเลขแรกของ 10 คือ 1 และลำดับที่ 11 คือตัวถัดไป คือ 0

เราต้องเขียนฟังก์ชัน JavaScript ที่รับตัวเลข n แล้วหาและคืนค่าตัวเลขธรรมชาติลำดับที่ n

ตัวอย่าง

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));

ผลลัพธ์

ผลลัพธ์ในคอนโซลจะเป็นดังนี้:

5 2 0 8