Java Program to Reverse Bits of a Number

Hello friends welcome to CodeSpeedy. In this tutorial, we will learn to reverse the bits of a number in Java.

Given a number say N we have to reverse the bits of the number and print the number obtained after reversing the bits.

For example:

Consider the number 22. The binary representation of 22 is 10110.

Therefore after reversing its bits we get 01101 which is 13.

Note: In the binary representation of the number we do not consider the leading zeros.

Java program to reverse the bits of Number

In the following method, we will obtain each bit of the number by performing the right shift on the given number.
We will store the bits obtained in another variable answer using the left shift operator.

ALGORITHM:

bitReverse(num)
{
    answer=0
    while num>0
    {
        answer = answer << 1
        if num & 1 == 1
        {
           answer = answer ^ 1
        }
        num = num >> 1
    }
    return answer
}

 

Following is the code snippet in java.

 

public class BitsReverse 
{
  static int bitReverse(int num)  /* function to reverse the bits */
  {
    int answer = 0;  /* to store the answer */
    
    while (num > 0)
    {
      answer = answer << 1;  /* performing bitwise left shift by 1 */
      
      if ((num & 1) == 1) /* checking if the current bit is 1 */
      {
        answer = answer ^ 1;  /* performing bitwise XOR operation */
      }
      
      num = num >> 1;  /* performing bitwise right shift by 1 */
    }
    
    return answer;
  }

  public static void main(String[] args) 
  {
    int num = 22;
    
    System.out.println("Number after reversing bits is ");
    System.out.println(bitReverse(num));
    
  }

}

OUTPUT:

Number after reversing bits is

13

Time Complexity: O(k) where k is the number of bits.

Leave a Reply

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