Friday, May 1, 2020

How to reverse bits of an integer in Java?

Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Guides

In this Java article, you will learn how to reverse bits of an integer in Java. This is one of the common coding problems which is often asked during phone round of technical interviews on companies like Amazon, Google, and Microsoft. If you have appeared in any programming interviews then there is a good chance that you might have already seen this problem before. If you know the solution then you are in a good place but if you don't know the solution then don't disappoint as many experienced Java developers also struggle to solve this problem. There are a couple of reasons for that, first not every Java developer is good with the bitwise operator, also understanding binary is not every programmer's cup of tea.

This is also a popular LeetCode coding problem, which I haven't tried to submit my solution, you can submit it. You may need to make some changes as they also have test cases which is run against the solution.

How to reverse bits of an integer in Java


Anyway, let's focus on the coding problem in the hand, here is the problem statement and sample input  and output given by interviewer:

Statement:  Given an integer, reverse its bit sequence.
Sample Input:  00000000000000001111111111111110
Sample Output: 01111111111111110000000000000000

This is a crucial junction in coding interviews. The interviewer has given you the problem and now either you can start working on them or spend some time thinking about it and ask some relevant questions to the interviewer to show that you pay attention to details and have good knowledge of how things work inside the machine.

In this problem, It is necessary to know whether the decimal number being passed as input is of type byte (8-bit) or short (16-bit) or int (32-bit) or long (64-bit): because Java will discard leading zeroes. Yes, that's the devil in the detail which many Java programmers don't know.

For example, if number = 0011010, Java will trim it to 11010 and then cause the reverse to look like 1011.  Under such cases, your reverse algorithm may not work.  To keep things simple, the presented algorithm treats int (32-bit)  inputs.

Java Program to reverse bits of an Integer in Java


Here is my sample program to reverse bits of an integer in Java. In this program, I have used an interactive algorithm to reverse all the bits of a given integer number. The number is passed as String from the console and that's why I have first converted given String to Integer using Integer.parseInt() method.

Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Guides

In some cases, the Interviewer can also ask why you use that particular method and why not Integer.valueOf() so be prepare for that.  If you need an answer then you can also see this article.  After that, I pass that integer to our method called the reverseBits(int number) which reverse the bits one at a time.

/**
 * Java Program to reverse bit sequence of an integer.
 * input : 11111111111111111111111111111110
 * output : 01111111111111111111111111111111
 *
 * @author WINDOWS 8
 */

public class ReverseBitsDemo {

    public static void main(String args[]) {

        System.out.println("Testing our reverseBits() method by"
                + " reversing ints in Java");
        String number = "000000000000000000000000000001";
        String expected = "10000000000000000000000000000000";
     
        int binary = Integer.parseInt(number, 2);
        int actual = reverseBits(binary);
     
        System.out.println("original number : " + number);
        System.out.println("reversed number : "
                       + Integer.toBinaryString(actual));
     
        System.out.println(expected.equals(Integer.toBinaryString(actual)));

    }

    /*
     * Java method to reverse bits of specified integer
     */
    public static int reverseBits(int number) {
        int sizeOfInt = 32;
        int reverse = 0;
        for (int position = sizeOfInt - 1; position > 0; position--) {
            reverse += ((number & 1) << position);
            number >>= 1;
        }
        return reverse;
    }

}

Output
Testing our reverseBits() method by reversing ints in Java
original number : 000000000000000000000000000001
reversed number : 10000000000000000000000000000000
true

That's all about how to reverse bits of an integer in Java. This is the brute force solution and there are some clever solutions also possible using a bitwise operator. If you know one, feel free to post into comments, that will help our readers a lot. I'll also be going to update the article with the top 3 clever solutions posted on comments.

This is also a popular LeetCode coding problem, which I haven't tried to submit my solution, you can and if you need more coding problems, particularly based upon bit manipulation then LeetCode has some good ones. If you need some resources to level up your essential skills, the following courses are highly recommended.

Related Posts

0 comments:

Post a Comment