Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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
Advertisements
