เราต้องเขียนฟังก์ชัน JavaScript ที่รับตัวเลขสองตัวเป็นอาร์กิวเมนต์ ให้เรียกว่า m และ n ตัวแรกมักจะเป็นตัวเลขหลายหลัก และตัวที่สองจะมีค่าน้อยกว่าจำนวนหลักของตัวแรกเสมอ
ฟังก์ชันต้องหากลุ่มของ n หลักติดต่อกันจาก m ที่ให้ผลคูณมากที่สุด
ตัวอย่าง
ถ้าตัวเลขนำเข้าคือ:
const m = 65467586; const n = 3;
ผลลัพธ์ควรเป็น:
const output = 280;
เพราะ 7 * 5 * 8 = 280 และนี่คือผลคูณสูงสุดของ 3 หลักติดต่อกันในตัวเลขนี้
ตัวอย่างโค้ด
const m = 65467586;
const n = 3;
const largestProductOfContinuousDigits = (m, n) => {
const str = String(m);
if(n > str.length) {
return 0;
}
let max = -Infinity;
let temp = 1;
for(let i = 0; i < n; i++) {
temp *= +(str[i]);
}
max = temp;
for(i = 0; i < str.length - n; i++) {
temp = (temp / (+str[i])) * (+str[i + n]);
max = Math.max(temp, max);
}
return max;
};
console.log(largestProductOfContinuousDigits(m, n));
ผลลัพธ์
280