From 1580f7193b1b644acabf6768e3f3e2517b3a0f54 Mon Sep 17 00:00:00 2001 From: Dusuna <94776135+dusunax@users.noreply.github.com> Date: Wed, 25 Dec 2024 20:03:52 +0900 Subject: [PATCH] add solution: reverse-bits --- reverse-bits/dusunax.py | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 reverse-bits/dusunax.py diff --git a/reverse-bits/dusunax.py b/reverse-bits/dusunax.py new file mode 100644 index 000000000..808d3efe4 --- /dev/null +++ b/reverse-bits/dusunax.py @@ -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