Skip to content

Commit

Permalink
add solution: reverse-bits
Browse files Browse the repository at this point in the history
  • Loading branch information
dusunax committed Dec 25, 2024
1 parent 8c1043e commit 1580f71
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions reverse-bits/dusunax.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
'''
# 190. Reverse Bits
SolutionA: using bin() and int() to convert the types.
SolutionB: using bitwise operations to reverse the bits.
## Time and Space Complexity
### SolutionA
```
TC: O(32) -> O(1)
SC: O(1)
```
### SolutionB
```
TC: O(32) -> O(1)
SC: O(1)
```
'''
class Solution:
'''
SolutionA
- using bin() and int() to convert the number to binary and back to integer.
- use .zfill(32) ensures that the binary string is always 32 bits long.
'''
def reverseBitsA(self, n: int) -> int:
bit = bin(n)[2:].zfill(32)
return int(bit[::-1], 2)

'''
SolutionB
- using bitwise operations to reverse the bits.
- iterate through the bits and reverse them.
'''
def reverseBitsB(self, n: int) -> int:
result = 0
for i in range(32):
result = (result << 1) | (n & 1) # shift the result to the left & add LSB of n
n >>= 1 # shift n to the right & remove previous LSB
return result

0 comments on commit 1580f71

Please sign in to comment.