Skip to content

Commit 1580f71

Browse files
committed
add solution: reverse-bits
1 parent 8c1043e commit 1580f71

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

reverse-bits/dusunax.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
'''
2+
# 190. Reverse Bits
3+
4+
SolutionA: using bin() and int() to convert the types.
5+
SolutionB: using bitwise operations to reverse the bits.
6+
7+
## Time and Space Complexity
8+
9+
### SolutionA
10+
```
11+
TC: O(32) -> O(1)
12+
SC: O(1)
13+
```
14+
15+
### SolutionB
16+
```
17+
TC: O(32) -> O(1)
18+
SC: O(1)
19+
```
20+
'''
21+
class Solution:
22+
'''
23+
SolutionA
24+
- using bin() and int() to convert the number to binary and back to integer.
25+
- use .zfill(32) ensures that the binary string is always 32 bits long.
26+
'''
27+
def reverseBitsA(self, n: int) -> int:
28+
bit = bin(n)[2:].zfill(32)
29+
return int(bit[::-1], 2)
30+
31+
'''
32+
SolutionB
33+
- using bitwise operations to reverse the bits.
34+
- iterate through the bits and reverse them.
35+
'''
36+
def reverseBitsB(self, n: int) -> int:
37+
result = 0
38+
for i in range(32):
39+
result = (result << 1) | (n & 1) # shift the result to the left & add LSB of n
40+
n >>= 1 # shift n to the right & remove previous LSB
41+
return result

0 commit comments

Comments
 (0)