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


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

Updated on: 19-Apr-2021

188 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements