Skip to main content

Reverse actual bits of the given number in java

Java program for Reverse actual bits of the given number. Here more information.

/*
  Java program for
  Reverse the bits of a number
*/
public class InvertBits
{
    // Reverse the bits element of a number
    public void reverseBits(int num)
    {

        int result = 0;
        // Assume num is positive integer
        int n = num;
        // Execute loop until, when the n is not zero
        while (n != 0)
        {
            if (result != 0)
            {
                result = result << 1;
            }
            if ((n & 1) == 1)
            {
                // When first bit is active
                result = result ^ 1;
            }
            n = n / 2;
        }
        // Display given number
        System.out.println("\n Number : " + num);
        // After the reversing bits
        System.out.println(" Output : " + result);
    }
    public static void main(String[] args)
    {
        InvertBits task = new InvertBits();
        // Test cases
        // ---------------
        // num = 16
        // 10000 => 00001 (1)
        task.reverseBits(16);
        // num = 35
        // 100011 => 110001 (49)
        task.reverseBits(35);
        // num = 20  
        // 10100  => 00101 (5)
        task.reverseBits(20);

    }
}

Output

 Number : 16
 Output : 1

 Number : 35
 Output : 49

 Number : 20
 Output : 5




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment