# Reverse Bits

Reverse bits of a given 32 bits unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).

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

Related problem: Reverse Integer

```>>> a = 10
>>> bin(a)
'0b1010'
>>> bin(a).replace('0b', '')
'1010'
>>> bin(a).replace('0b', '')[::-1]
'0101'
>>> '0b' + bin(a).replace('0b', '')[::-1]
'0b0101'
>>> int('0b' + bin(a).replace('0b', '')[::-1], 2)
5```

```class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
return int('0b' + bin(n).replace('0b', '')[::-1], 2)```

```Submission Result: Wrong Answer

Input:	           1 (00000000000000000000000000000001)
Output:	           1 (00000000000000000000000000000001)
Expected:	  2147483648 (10000000000000000000000000000000)
```

```>>> a = 1
>>> bin(a)
'0b1'
>>> bin(a).replace('0b', '')
'1'
>>> bin(a).replace('0b', '')[::-1]
'1'```

0b00……1010，前面有28个0，进行颠倒之后变成0b010100……0000，后面有28个0

0 + 1 * 2 ^ (32 – 4) + 0 * 2 ^ (32 – 3) + 1 * 2 ^ (32 – 2) + 0 * 2 ^ (32 – 1)

4就是n转换成二进制的长度，如此看来值需要得到二进制位长度，颠倒后二进制转换成十进制，其实也就是颠倒前二进制倒着转换成十进制，倒着意思就是从高位到低位依次乘以2^0, 2^1……，一直到2^31，这样就很好遍历了

```class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
a = bin(n).replace('0b', '')
i = 32 - len(a)
sum = 0
for b in a:
sum += int(b) * int(math.pow(2, i))
i += 1
return sum```

```600 / 600 test cases passed.
Status: Accepted
Runtime: 76 ms```