Problem Statement in English
You’re given a 32 bit integer n. Your task is to reverse the bits in its binary representation and return the resulting number.
Step 1: Extract last bit from n
Step 1.1: Use a bitwise AND operation to find if the last bit is or :
If we use a bitwise AND between a number and , we end up with if the last bit of the number is , and otherwise. For example:4 & 1 = 0, as , and . When we use bitwise AND, we get .7 & 1 = 1, as , and . When we use bitwise AND, we get .
Step 1.2: Perform a right shift operation on
n:
This removes the last bit fromn.
Step 2: Update buff
Step 2.1: Use a right shift operation on
buffin order to create a vacancy at its LSB (least significant bit):
When we left shift a number, all its bits move left once, creating a new space at its LSB.Step 2.2: Use a bitwise OR to insert the extracted bit from ‘Step 1’ into the newly created space:
The new LSB will always be , as that’s what happens when you left shift a number. When we use a bitwise OR against that 0:- and try to insert a ,
0 | 1 = 1 - and try to insert a ,
0 | 0 = 0
- and try to insert a ,
Step 3: Repeat until n is
- Step 3.1: We need to have removed all the bits from
n:
Step 4: Pad buff to get it to bits
- Step 4.1: If the number of bits in
buffis less than , keep padding with s on the LSB:
If the input number is, for example, , then we only get 2 bits since . But we need to have 32 bits, so we need to left shiftbuffmore times.
Solution in Python
class Solution:
def reverseBits(self, n: int) -> int:
buff = 0
temp = 0
done = 0
while n > 0:
temp = n & 1
n = n >> 1
buff = buff << 1
buff = buff | temp
done += 1
buff = buff << (32 - done)
return buff
Complexity
Time:
Since we only need left shifts at most forn, and right shifts at most forbuff.Space:
We only use a couple integer variables.
And we are done.