- Related Questions & Answers
- Write a program to reverse digits of a number in C++
- Write an Efficient Method to Check if a Number is Multiple of 3 in C++
- Write a C program to reverse array
- Reverse Bits in C++
- Python program to reverse bits of a positive integer number?
- Java program to reverse bits of a positive integer number
- Write a program to reverse an array or string in C++
- C++ Program to Reverse a Number
- Write a Golang program to reverse a number
- Program to invert bits of a number Efficiently in C++
- Write a Golang program to reverse an array
- Write a program to reverse an array in JavaScript?
- C# program to count total bits in a number
- Write a python program to count total bits in a number?
- C# program to reverse an array

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

In this problem, we are given an unsigned integer n. Our task is to create a program that returns the number which is generated by reversing all the bits of the number.

Let’s take an example to understand the problem,

n = 1

2147483648

binary of 1 is 000...0001, the reverse is 100...0000.

To solve this problem, we simple solution will be using a simple formula. We will loop through the binary of the number. And find the position of the set bit in the number lets say it i. The result will be calculated using the formula, ((total_number_of_bits) - 1) - i

Program to show the implementation of this algorithm,

#include<iostream> using namespace std; unsigned int reverseBitNumber(unsigned int num) { unsigned int totalNumberOfBits = sizeof(num) * 8; unsigned int reverseNumber = 0, temp; for (int i = 0; i < totalNumberOfBits; i++){ if((num & (1 << i))) reverseNumber |= (1 << ((totalNumberOfBits - 1) - i)); } return reverseNumber; } int main() { unsigned int n = 21; cout<<"The number is "<<n<<endl; cout<<"The number which has reverse bits of the number is :"<<reverseBitNumber(n); return 0; }

The number is 2 The number which has reverse bits of the number is :2818572288

Another method is using shifting, we will shift the bits of the number until it become zero and the shift them in reverse number and then shift the bits remaining number of times to get the result.

Program to show the implementation of our solution,

#include<iostream> using namespace std; unsigned int reverseBitNumber(unsigned int n){ unsigned int rem_shift = sizeof(n) * 8 - 1; unsigned int reverseNubmer = n; n >>= 1; while(n){ reverseNubmer <<= 1; reverseNubmer |= n & 1; n >>= 1; rem_shift--; } reverseNubmer <<= rem_shift; return reverseNubmer; } int main(){ unsigned int n = 21; cout<<"The number is "<<n<<endl; cout<<"The number which has reverse bits of the number is :"<<reverseBitNumber(n); return 0; }

The number is 21 The number which has reverse bits of the number is :2818572288

Advertisements