Dãy số tự nhiên: 1,2,3,... Ghép thành chuỗi chữ số: 123456789101112... Tìm chữ số ở vị trí n.
Ví dụ
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));
Kết quả
5 2 0 8