
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Reverse Bits of a 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 −
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
Advertisements