Reverse actual bits of the given number in Java


Given an integer n that is not negative. The goal is to reverse the bits of n and report the number that results from doing so. While reversing the bits, the actual binary form of the integer is used; no leading 0s are taken into account.

Let us see various input output scenarios for this

Input − 13

Output − Reverse actual bits of the given number 11

(13)10 = (1101)2.
After reversing the bits, we get:
(1011)2 = (11)10.

Explanation − The binary bits are obtained from the input number which is then reversed and finally converted to decimal format which is returned as output.

Input − 18

Output − Reverse actual bits of the given number 9

(18)10 = (10010)2.
After reversing the bits, we get:
(1001)2 = (9)10.

Explanation −The binary bits are obtained from the input number which is then reversed and finally converted to decimal format which is returned as output.

Approach used in the below program is as follows

  • Inside the main method

    • The number is taken input and passed in the method reverseBinaryBits(int input)

  • Inside the method reverseBinaryBits(int input)

    • A variable rev_input is initialized to store reversed bits

    • A loop is iterated with breaking point(input > 0)(we are traversing from the right)

      • The bitwise right shift operation is used to retrieve one by one bits in the binary representation of n, and the bitwise left shift operation is used to accumulate them in rev.

Example

class TutorialsPoint{
   public static int reverseBinaryBits(int input){
      int rev_input = 0;
      while (input > 0){
         rev_input <<= 1;
         if ((int) (input & 1) == 1){
            rev_input ^= 1;
         }
         input >>= 1;
      }
      return rev_input;
   }
   public static void main(String[] args){
      int input = 13;
      System.out.println("Reverse actual bits of the given number");
      System.out.println(reverseBinaryBits(input));
   }
}

Output

If we run the above code it will generate the following Output

Reverse actual bits of the given number
11

Updated on: 03-Nov-2021

838 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements