Flipping Bits


In this article we will try to solve one of the problem from Hacker Rank. The problem is called Flipping Bits.

You will be given a list of 32 bit unsigned integers. Flip all the bits (1 –> 0 and 0 –> 1) and return the result as an unsigned integer.


n = 910
910 = 10012
In 32 bits it will be represented as 000000000000000000000000000010012
The inverted bits will be 11111111111111111111111111111101102 which represents 429496728610


Let’s see how we are going to solve this problem. First we will convert long to int by casting it:


Now we will use the NOT operator to toggle the 1s to0s and 0s to 1s


Now we will use the toUnsignedLong() method in Integer class to convert the argument to a long by an unsigned conversion.


In an unsigned conversion to a long, the high-order 32 bits of the long are zero and the low-order 32 bits are equal to the bits of the integer argument. Consequently, zero and positive int values are mapped to a numerically equal long value and negative int values are mapped to a long value equal to the input plus 232


public class FlippingBits {

    static long flippingBits(long n) {
        return Integer.toUnsignedLong(~(int)n);


In this article we saw how to flip all the bits of the given number to get an unsigned converted number.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: