使用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