使用JavaScript检查缺数
当一个数:−
至少有三位数,且
能被其首位数字和末位数字组合成的数整除
例如
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;
//receives a number string and returns a boolean
const isGapful = (numStr) => {
const int = parseInt(numStr);
return int % parseInt(numStr[0] + numStr[numStr.length - 1]) === 0;
};
//main function -- receives a number, returns a number
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP