ภาพรวม
บทความนี้สาธิตวิธีหาตัวเลขที่มากที่สุดในตัวเลขที่กำหนด โดยใช้ Recursive Function เช่น 45654356 -> 6
การนำไปใช้ (Recursive)
const greatestDigit = (num = 0, greatest = 0) => {
if (num) {
const max = Math.max(num % 10, greatest);
return greatestDigit(Math.floor(num / 10), max);
}
return greatest;
};
console.log(greatestDigit(45654356)); // 6
ผลลัพธ์
6
วิธีการ Iterative (แนะนำ - ไม่มี Stack Overflow Risk)
const greatestDigitIterative = (num) => {
let greatest = 0;
num = Math.abs(num); // จัดการตัวเลขติดลบ
while (num > 0) {
greatest = Math.max(greatest, num % 10);
num = Math.floor(num / 10);
// Early exit: ถ้าเจอ 9 แล้ว ไม่ต้องหาต่อ
if (greatest === 9) break;
}
return greatest;
};
วิธีการทันสมัย (Functional)
const greatestDigitModern = (num) =>
Math.max(...String(Math.abs(num)).split('').map(Number));
// หรือ
const greatestDigitModern2 = (num) =>
[...String(Math.abs(num))].reduce((max, d) => Math.max(max, +d), 0);
การประยุกต์ใช้
- Digit Analysis / Statistics
- Check Digit Calculation (Luhn Algorithm)
- Number Theory Problems
- Game Development: Dice Roll Analysis
ข้อควรระวัง
- Recursive Version: จำกัดโดย Call Stack (~10,000-15,000 หลัก)
- ตัวเลข 0: ต้องจัดการแยก (คืนค่า 0)
- ตัวเลขติดลบ: ใช้ Math.abs()
- BigInt: ใช้ toString() แล้วประมวลผล
Benchmark (ประมาณ)
// Iterative: ~50M ops/sec
// String/Spread: ~10M ops/sec
// Recursive: ~5M ops/sec (และจำกัดความลึก)