![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 in C++
Suppose we have one unsigned number x, and we can easily find the binary representation of it (32bit unsigned integer). Our task is to reverse the bits. So if the binary representation is like 00000000000000000000001001110100, then reversed bits will be 00101110010000000000000000000000. So we have to return the actual number after reversing the bits
To solve this, we will follow these steps −
- Suppose n is the given number
- let answer := 0
- for i := 31 down to 0:
- answer := answer OR (n AND i), and shift it to the left i times
- n := n after right shifting 1 bit
- return answer
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: uint32_t reverseBits(uint32_t n) { uint32_t ans = 0; for(int i = 31; i >= 0; i--){ ans |= (n & 1) <<i; n>>=1; } return ans; } }; main(){ Solution ob; cout << ob.reverseBits(0b00000000000000000000001001110100); }
Input
0b00000000000000000000001001110100
Output
775946240
Advertisements