JavaScript - 查找最小的 n 位数字或更大数字

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/7 6:36:17

我们需要编写一个 JavaScript 函数,该函数将数字作为第一个参数(例如 n),将数字数组作为第二个参数。该函数应返回最小的 n 位数字,该数字是数组中指定的所有元素的倍数。如果不存在这样的 n 位元素,则我们应该返回最小的此类元素。

例如:如果数组为 −

const arr = [12, 4, 5, 10, 9]

对于 n = 2 和 n = 3,输出应为 180

示例

以下是代码 −

const arr = [12, 4, 5, 10, 9]
const num1 = 2;
const num2 = 3;
const allDivides = (arr, num) => arr.every(el => num % el === 0);
const smallestMultiple = (arr, num) => {
   let smallestN = Math.pow(10, (num - 1));
   while(!allDivides(arr, smallestN)){
      smallestN++;
   };
   return smallestN;
};
console.log(smallestMultiple(arr, num1));
console.log(smallestMultiple(arr, num2));

输出

以下是控制台中的输出 −

180
180

相关文章


有用资源