Viết hàm nhận hai số m (số nhiều chữ số) và n (số chữ số liên tiếp, n < độ dài m). Tìm nhóm n chữ số liên tiếp của m có tích lớn nhất.
Ví dụ: m=65467586, n=3 → 280 (7×5×8=280).
Ví dụ
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 (let 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));
Kết quả
280