เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่ใช้ตัวเลขสองตัวเป็นอาร์กิวเมนต์ตัวแรกและตัวที่สอง ให้เราเรียกมันว่า m และ n
โดยทั่วไป ตัวเลขแรกจะเป็นตัวเลขที่มีหลายหลัก และตัวเลขที่สองมักจะน้อยกว่าจำนวนหลักในตัวเลขแรกเสมอ
ฟังก์ชันควรค้นหากลุ่มของ n หลักต่อเนื่องกันจาก m ซึ่งผลคูณมีค่ามากที่สุด
ตัวอย่างเช่น −
หากตัวเลขที่ป้อนคือ −
const m = 65467586; const n = 3;
จากนั้นผลลัพธ์ควรเป็น −
const output = 280;
เพราะ 7 * 5 * 8 =280 และเป็นผลคูณสามหลักสูงสุดในตัวเลขนี้
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
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