ตัวเลขเป็นจำนวนช่องว่างเมื่อ -
-
มีอย่างน้อยสามหลักและ
-
หารด้วยจำนวนที่เกิดขึ้นโดยนำหลักแรกและหลักสุดท้ายมาหารกันอย่างลงตัว
ตัวอย่าง:
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