

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 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
- Related Questions & Answers
- Reverse actual bits of the given number in Java
- JavaScript Reverse the order of the bits in a given integer
- Python program to reverse bits of a positive integer number?
- Java program to reverse bits of a positive integer number
- Write an Efficient C Program to Reverse Bits of a Number in C++
- Array reverse() vs reverse! in Ruby
- String reverse vs reverse! function in Ruby
- Counting Bits in Python
- Reverse numbers in function without using reverse() method in JavaScript
- Reverse Integer in Python
- Reverse String in Python
- Array reverse() in JavaScript
- Reverse Pairs in C++
- Print numbers having first and last bits as the only set bits
- Number of 1 Bits in Python
Advertisements