เรารู้ว่าจำนวนธรรมชาติในวิชาคณิตศาสตร์เป็นตัวเลขที่เริ่มต้นจาก 1 และขยายเป็นอนันต์
ตัวเลขธรรมชาติ 15 ตัวแรกคือ −
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
ดังนั้น หลักธรรมชาติตัวแรกคือ 1 ตัวที่สองคือ 2 ตัวที่สามคือ 3 ไปเรื่อยๆ แต่เมื่อเราเกิน 9 หลักธรรมชาติที่สิบจะเป็นหลักแรกของ 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