Reverse Bits
Given a 32-bit unsigned integer n, reverse the bits of the binary representation of n and return the result.
Example 1:
Input: n = 00000000000000000000000000010101
Output: 2818572288 (10101000000000000000000000000000)
Explanation: Reversing 00000000000000000000000000010101, which represents the unsigned integer 21, gives us 10101000000000000000000000000000 which represents the unsigned integer 2818572288.
Solution
We can convert the number into a binary number and store its bits, then sum up the bits in reverse order.
Or actually we don't need to store the bits, as we've already known where the bit will be after reversion.
Code
Convert and store:
py
class Solution:
def reverseBits(self, n: int) -> int:
bits = []
while n > 0:
bits.append(n%2)
n //= 2
while len(bits) < 32:
bits.append(0)
ans = 0
for bit in bits:
ans <<= 1
ans += bit
return ans
No store:
py
class Solution:
def reverseBits(self, n: int) -> int:
ans = 0
for i in range(32):
bit = (n >> i) & 1
ans += bit<<(31-i)
return ans