Bitwise Operators: Program to reverse the bits of a number

Problem Statement:

You are given a number, reverse all the bits of the number.

Example:

Input : n = 1
Output : 2147483648

Solution 1:

Loop through all the bits of an integer.

If the bit is set in the ith position, then set the bit at (NO_OF_BITS – 1) – i in output.

NO_OF_BITS represents the number if bits of a given number.

Code Solution

#include<iostream>
using namespace std;

 
unsigned int solution_1(unsigned int num)
{
    unsigned int NO_OF_BITS = sizeof(num) * 8;
    
    unsigned int reverse_num = 0;
    
    int i;
    
    for (i = 0; i < NO_OF_BITS; i++) {
        if ((num & (1 << i)))
            reverse_num |= 1 << ((NO_OF_BITS - 1) - i);
    }
    return reverse_num;
}

int main()
{
    unsigned int x = 1;
    cout << solution_1(x);
    return 0;
}

Output

2147483648

 

 

 

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *