JavaScript 中一个数字 n 个连续数字最大乘积
我们需要编写一个 JavaScript 函数,它接收两个数字作为第一个和第二个参数,我们称之为 m 和 n。
第一个数字通常是一个多位数,第二个数字通常小于第一个数字的位数。
该函数应该从 m 中找到 n 个连续数字组,其乘积最大。
例如 −
如果输入数字是 −
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
广告