在 JavaScript 中查找有间隙数

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/1 18:20:17

如果一个数至少有 3 位数字,并且能被第一个和最后一个数字串在一起形成的数整除,则该数为有间隙数。符合此描述的最小数是 100。第一个数字是 1,最后一个数字是 0,形成 10,是 100 的因数。因此,100 是有间隙数的。

我们需要创建一个函数,该函数接受一个数 n 并返回最接近的有间隙数(包括其本身)。如果有 2 个有间隙数与 n 等距,则返回较小的一个。

一些例子 −

gapful(25) ➞ 100

gapful(100) ➞ 100

gapful(103) ➞ 105

示例

以下是代码 −

const num = 4780;
const isGapful = n => {
   if (n < 100){
      return false;
   }
   const temp = Array.from(n.toString());
   return n % (temp[0] + temp[temp.length - 1]) === 0;
}
function getClosestGapful(n) {
   let left = n, right = n;
   while (!isGapful(right)){
      right++;
   }
   if (n < 100){
      return right;
   }
   while (!isGapful(left)){
      left++;
   }
   return n - left <= right - n ? left : right;
};
console.log(getClosestGapful(25));
console.log(getClosestGapful(num));

输出

这将在控制台上产生以下输出 −

100
4800

相关文章


有用资源