Checking for the Gapful numbers in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

A number is a gapful number when −

  • It has at least three digits, and

  • It is exactly divisible by the number formed by putting its first and last digits together

For example:

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.

Our job is to write a program that returns the nearest gapful number to the number we provide as input.

Let’s write the code −

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));

The output in the console will be −

135
raja
Published on 09-Oct-2020 11:51:53
Advertisements