检查JavaScript中的Gapful数字
当-时,数字为空数-
它至少包含三位数,并且
可以通过将第一位和最后一位放在一起形成的数字来整除
例如:
1053 is a gapful number because it has 4 digits and it is exactly divisible by 13. 135 is a gapful number because it has 3 digits and it is exactly divisible by 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