# 190. Reverse Bits (Easy)

https://leetcode.com/problems/reverse-bits/

Reverse bits of a given 32 bits unsigned integer.

Example 1:

```Input: 00000010100101000001111010011100
Output: 00111001011110000010100101000000
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.
```

Example 2:

```Input: 11111111111111111111111111111101
Output: 10111111111111111111111111111111
Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10101111110010110010011101101001.```

Note:

• Note that in some languages such as Java, there is no unsigned integer type. In this case, both input and output will be given as signed integer type and should not affect your implementation, as the internal binary representation of the integer is the same whether it is signed or unsigned.
• In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 2 above the input represents the signed integer `-3` and the output represents the signed integer `-1073741825`.

If this function is called many times, how would you optimize it?

## Solutions

### 1.

``````public class Solution {

// switch bits from ith to (31-i)th, where i in [0, 31]

public int reverseBits(int n) {
// In case of overflow issue, return 1 if n is Integer.MIN_VALUE.
if (n == (1 << 31)) {
return 1;
}

if (n == 0) {
return 0;
}

int ans = 0;
for (int i = 0; i <= 31; i++) {
int x = 1 << i;
if ((x & n) != 0) {
ans = ans | (1 << (31 - i));
}
}

return ans;
}
}
``````

### 2.

``````public class Solution {

// Do not assume that positive values are similar with negative value that of same absolute vaulue.
// Take 1 and -1 as examle, bit representation is totally different, not only differ in the sign bit, but almost all bits.
// 1 is 0....1, but -1 is 1....1, only the last bit is the same.

public int reverseBits(int n) {
// In case of overflow issue, return 1 if n is Integer.MIN_VALUE.
if (n == (1 << 31)) {
return 1;
}

if (n == 0) {
return 0;
}

int ans = 0;

// The last bit is 1, move it to the head.
if (n % 2 != 0) {
ans = 1 << 31;
}

// since n < 0, the first bit is 1, swap it to the end.
if (n < 0) {
ans += 1;
}

// turn the value to positive if n is negative.
int tmp = n;
if (n < 0) {
tmp = Integer.MAX_VALUE - Math.abs(n) + 1;
}

// Do not deal with the first and end bits in the loop, it's trivial and easy to bring in bugs.
// Only work on bits from 1 to 31
for (int i = 1; i < 31; i++) {
if ((tmp & (1 << i)) > 0) {
ans += 1 << (31 - i);
}
}

return ans;
}
}
``````