Reverse 32-bit Integer in Python

🚀 Coding Practice — Reverse Bits (32-bit Integer) Today I practiced a classic bit manipulation problem: reversing the bits of a 32-bit unsigned integer. 🧠 Intuition The idea is simple and systematic: • Convert the number into its binary representation • Ensure the binary string is exactly 32 bits long • Reverse the binary string • Convert the reversed binary back into an integer Since Python makes string operations easy, reversing bits becomes very straightforward using slicing. ⚙️ Approach 1️⃣ Convert n to binary using bin(n)[2:] to remove the 0b prefix 2️⃣ Pad with leading zeros to make it 32 bits 3️⃣ Reverse the string using slicing [::-1] 4️⃣ Convert back to integer using int(binary, 2) ⏱️ Complexity • Time Complexity: O(1) — fixed at 32 bits • Space Complexity: O(1) — only a constant-size string is stored 💻 Python Implementation class Solution(object): def reverseBits(self, n): bits = bin(n)[2:] bits = "0" * (32 - len(bits)) + bits return int(bits[::-1], 2) Bit manipulation problems look tricky at first — but with the right breakdown, they become very manageable. #Python #CodingPractice #BitManipulation #DataStructures #Algorithms #LeetCode #ProblemSolving #SoftwareDevelopment #FresherDeveloper #InterviewPreparation

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories