Reversing the bits of a decimal number and returning new decimal number in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a decimal number, converts it into binary and reverses its 1 bit to 0 and 0 to 1 and returns the decimal equivalent of new binary thus formed.

Example

Following is the code −

 Live Demo

const num = 45657;
const reverseBitsAndConvert = (num = 1) => {
   const binary = num.toString(2);
   let newBinary = '';
   for(let i = 0; i < binary.length; i++){
      const bit = binary[i];
      newBinary += bit === '1' ? '0' : 1;
   };
   const decimal = parseInt(newBinary, 2);
   return decimal;
};
console.log(reverseBitsAndConvert(num));

Output

19878
raja
Published on 19-Apr-2021 11:31:49
Advertisements