File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments