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 −
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