Given an integer, reverse its bits using binary operators.

For example, -100 in binary is 11111111111111111111111110011100. On reversing its bits, we get number 973078527 which is 00111001111111111111111111111111 in binary.

Practice this problem

The idea is to initialize the result by 0 (all bits 0) and process the given number starting from its least significant bit. If the current bit is 1, set the corresponding most significant bit in the result and finally move on to the next bit in the input number. Repeat this till all its bits are processed.

Following is the implementation in C++, Java, and Python based on the above idea:

C++


Download  Run Code

Output:

-100 in binary is 11111111111111111111111110011100
On reversing bits 00111001111111111111111111111111

Java


Download  Run Code

Output:

-100 in binary is 11111111111111111111111110011100
On reversing bits 00111001111111111111111111111111

Python


Download  Run Code

Output:

-100 in binary is-0b1100100
On reversing bits 0b111001111111111111111111111111

The above solution will process all bits in an integer till its last set bit. The code can be optimized to consider only set bits in an integer (which will be relatively less). The idea is to find the position of the rightmost set bit in the number and set the corresponding bit in the result, and finally, unset the rightmost set bit. Repeat this till all set bits are processed.

Please refer to this post to find the position of the rightmost set bit and unset it. The algorithm can be implemented as follows in C++ and Java:

C++


Download  Run Code

Output:

-100 in binary is 11111111111111111111111110011100
On reversing bits 00111001111111111111111111111111

Java


Download  Run Code

Output:

-100 in binary is 11111111111111111111111110011100
On reversing bits 00111001111111111111111111111111

 
Read More:

Reverse bits of an integer using a lookup table