在 JavaScript 中检查有间隙数字
javascriptweb developmentobject oriented programming更新于 2026/1/16 22:36:17
当 − 时,数字就是有间隙数字。
它至少有三位数,并且
它可以被其首位和末位数字相加而成的数字整除
例如:
1053 是一个有间隙数字,因为它有 4 位数字,并且可以被 13 整除。 135 是一个有间隙数字,因为它有 3 位数字,并且可以被 15 整除。
我们的工作是编写一个程序,返回最接近我们输入的数字的有间隙数字。
让我们编写代码 −
const n = 134;
//接收一个数字字符串并返回一个布尔值
const isGapful = (numStr) => {
const int = parseInt(numStr);
return int % parseInt(numStr[0] + numStr[numStr.length - 1]) === 0;
};
//主函数 - 接收一个数字,返回一个数字
const nearestGapful = (num) => {
if(typeof num !== 'number'){
return -1;
}
if(num <= 100){
return 100;
}
let prev = num - 1, next = num + 1;
while(!isGapful(String(prev)) && !isGapful(String(next))){
prev--;
next++;
};
return isGapful(String(prev)) ? prev : next;
};
console.log(nearestGapful(n));
控制台中的输出将是 −
135
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

