Next multiple of 5 and binary concatenation in JavaScript


Problem

We are required to write a JavaScript function that takes in a number n. Our function should return the next higher multiple of five of that number, obtained by concatenating the shortest possible binary string to the end of this number's binary representation.

Example

Following is the code −

const generateAll = (num = 1) => {
   const res = [];
   let max = parseInt("1".repeat(num), 2);
   for(let i = 0; i <= max; i++){
      res.push(i.toString(2).padStart(num, '0'));
   };
   return res;
};
const smallestMultiple = (num = 1) => {
   const numBinary = num.toString(2);
   let i = 1;
   while(true){
      const perm = generateAll(i);
      const required = perm.find(binary => {
         return parseInt(numBinary + binary, 2) % 5 === 0;
      });
      if(required){
         return parseInt(numBinary + required, 2);
      };
      i++;
   };
};
console.log(smallestMultiple(8));

Output

35

Updated on: 19-Apr-2021

58 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements