# Flipping Bits

## Overview

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.

Example

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

## Code

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

```(int)n
```

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

```~(int)n
```

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

```Integer.toUnsignedLong(~(int)n)
```

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

FlippingBits.java

```public class FlippingBits {

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

## Conclusion

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