🚀 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
Reverse 32-bit Integer in Python
More Relevant Posts
-
𝐌𝐚𝐬𝐭𝐞𝐫𝐢𝐧𝐠 𝐏𝐲𝐭𝐡𝐨𝐧 𝐋𝐨𝐨𝐩𝐬: 𝐓𝐡𝐞 𝐎𝐧𝐥𝐲 𝐓𝐰𝐨 𝐓𝐡𝐚𝐭 𝐌𝐚𝐭𝐭𝐞𝐫. 🔄 𝐖𝐡𝐞𝐧 writing Python, iteration is a core part of our daily workflow. But despite all the advanced techniques out there, Python technically only has two real loop statements: the for loop and the while loop[cite: 289, 290, 291]. Everything else we use is simply a pattern, a control feature, or a syntax shortcut[cite: 292]. 𝐔𝐧𝐝𝐞𝐫𝐬𝐭𝐚𝐧𝐝𝐢𝐧𝐠 when to use which is the key to writing clean and efficient code. The for loop is best when you are working with known collections like lists, strings, or dictionaries[cite: 297, 298]. The while loop is your go-to when the number of repeats is unknown and depends on a specific condition remaining True[cite: 305, 306]. 𝐊𝐞𝐲 𝐂𝐨𝐧𝐜𝐞𝐩𝐭𝐬 𝐭𝐨 𝐊𝐧𝐨𝐰:- • 𝐋𝐨𝐨𝐩 𝐂𝐨𝐧𝐭𝐫𝐨𝐥𝐬: Use break to stop a loop immediately [cite: 329, 330], or continue to skip the current iteration and move to the next[cite: 331, 332]. • 𝐂𝐨𝐦𝐩𝐫𝐞𝐡𝐞𝐧𝐬𝐢𝐨𝐧𝐬: List, set, and dictionary comprehensions are compact, Pythonic iteration shortcuts[cite: 342, 343, 344]. They are not new loops, just cleaner ways to write them. • 𝐓𝐡𝐞 𝐞𝐥𝐬𝐞 𝐂𝐥𝐚𝐮𝐬𝐞: A unique Python feature where an else block runs only if the loop ends naturally without hitting a break statement[cite: 336, 337, 338]. Conclusion:- 𝐔𝐥𝐭𝐢𝐦𝐚𝐭𝐞𝐥𝐲, becoming a strong engineer means you must master logic, not just syntax[cite: 352]. By deeply understanding these two fundamental loops, you can build any complex iteration pattern required for your system. Special thanks to my mentor Mian Ahmad Basit for the continued guidance. #MuhammadAbdullahWaseem #Nexskill #PythonProgramming #SoftwareEngineering #Pakistan #Ramadan
To view or add a comment, sign in
-
-
**Dangerous Python** **Artifact #2 -> a function whose AST is rewritten before execution** Most programmers think code lives in two moments: first, it is written then, it runs Python allows a third. A program can inspect its own structure before that structure becomes execution. That structure is the AST. The Abstract Syntax Tree. Not the source text. Not yet the bytecode. The internal shape of the program. And yes, it can be modified. Which means code may begin in one form and execute in another. Same name. Same function. Different structure. This is deeper than runtime mutation. In Artifact #1, the function changed its engine while running. In Artifact #2, we go lower. We change the syntactic skeleton before the function fully comes into existence. That is what makes AST rewriting so powerful and so dangerous. Because now a program is no longer just something that runs. It can read itself. Transform itself. Recompile itself. Return as something else. Useful in compilers, linters, instrumentation, symbolic systems, and code generation. But in normal application code, this feels less like engineering and more like opening the back door of the language. Artifact #1 changed the engine. Artifact #2 changes the blueprint. Example below. PYTHON ALLOWS SOMETHING EVEN STRANGER: A FUNCTION MAY ARRIVE IN EXECUTION WEARING THE SAME NAME, WHILE CARRYING A DIFFERENT STRUCTURE THAN THE ONE THAT WAS WRITTEN. NOT PATCHED AFTERWARD. REWRITTEN BEFORE BIRTH. #Python #Metaprogramming #AST #SoftwareEngineering #Programming
To view or add a comment, sign in
-
-
🚀 Coding Practice — Prime Number of Set Bits (Bit Manipulation) Today I solved an interesting bit manipulation problem: 👉 Given two integers left and right, count how many numbers in the range [left, right] have a prime number of set bits in their binary representation. 🧠 Problem Understanding A set bit means a 1 in binary representation. Example: 21 → 10101 → 3 set bits We must: Convert each number in range [left, right] to binary Count number of 1s Check if that count is prime Return total count 🔍 Key Insight (Optimization Trick) Given constraint: 1 ≤ left ≤ right ≤ 10^6 0 ≤ right - left ≤ 10^4 Maximum number of bits required for 10^6: log₂(10^6) ≈ 20 So maximum possible set bits = 20 That means we only need to check primes up to 20: {2, 3, 5, 7, 11, 13, 17, 19} ⚡ Instead of checking prime every time, we store these in a set for O(1) lookup. ✅ Optimized Python Solution class Solution: def countPrimeSetBits(self, left: int, right: int) -> int: # Prime numbers up to 20 (maximum possible set bits) primes = {2, 3, 5, 7, 11, 13, 17, 19} count = 0 for num in range(left, right + 1): set_bits = num.bit_count() # Fast built-in method if set_bits in primes: count += 1 return count 🔎 Example 1 Input: left = 6, right = 10 NumberBinarySet BitsPrime?61102✅71113✅810001❌910012✅1010102✅ ✔ Output = 4 ⏱ Complexity Analysis Time Complexity: O(N) where N = right - left (max 10^4) Space Complexity: O(1) Very efficient and well within constraints. #Python #CodingPractice #BitManipulation #ProblemSolving #DataStructures #InterviewPreparation #LeetCode
To view or add a comment, sign in
-
-
🧠 Python Concept: List Comprehension Write powerful loops in one clean line. ❌ Traditional Way squares = [] for i in range(5): squares.append(i * i) print(squares) Output [0, 1, 4, 9, 16] ✅ Pythonic Way squares = [i * i for i in range(5)] print(squares) Same result, less code. ⚡ With Condition even_squares = [i * i for i in range(10) if i % 2 == 0] print(even_squares) Output [0, 4, 16, 36, 64] 🧒 Simple Explanation Imagine telling a robot: 👉 “Give me squares of numbers from 0–4.” 👉 Instead of repeating instructions, you give one rule. 👉 That rule = list comprehension. 💡 Why This Matters ✔ Shorter code ✔ Faster execution ✔ More readable loops ✔ Very Pythonic 🐍 Python often replaces multiple lines with a single elegant expression 🐍 List comprehensions are one of the most powerful examples of that philosophy. #Python #PythonTips #PythonTricks #AdvancedPython #List #ListComprehension #Tech #CleanCode #LearnPython #Programming #DeveloperLife #DailyCoding #100DaysOfCode
To view or add a comment, sign in
-
-
Let’s keep it simple (and a little fun today 😄) Which of the following is a valid list comprehension in Python? A) [x for x in range(5) if x % 2 == 0] B) for x in range(5): if x % 2 == 0 C) x = [range(5) if x % 2 == 0] D) list(x for x in range(5) if x % 2 == 0) 🧠 The correct answer is: 👉 A [x for x in range(5) if x % 2 == 0] This is the classic Pythonic structure: [expression for item in iterable if condition] ✨ Option D technically works and returns a list, but A is the clean, direct list comprehension syntax. Small concept. Big readability difference. Clean code isn’t about writing more… It’s about writing smarter 🔥 #Python #AI #LearningInPublic #30DayChallenge #DataAnalytics #CleanCode
To view or add a comment, sign in
-
🚀 Day 48 of #100DaysOfCode I recently tackled an interesting coding problem: “Given a binary number as a string, find the number of steps to reduce it to 1. If even, divide by 2; if odd, add 1.” For example: Input: "1101" → Output: 6 Input: "10" → Output: 1 Input: "1" → Output: 0 Instead of converting the binary to decimal, I simulated the steps directly on the binary string, which makes it efficient even for very long numbers. Here’s the Python solution I implemented: def numSteps(s: str) -> int: steps = 0 s = list(s) while len(s) > 1: if s[-1] == '0': s.pop() else: i = len(s) - 1 while i >= 0 and s[i] == '1': s[i] = '0' i -= 1 if i >= 0: s[i] = '1' else: s.insert(0, '1') steps += 1 return steps print(numSteps("1101")) # 6 💡 Key Takeaways: You can work directly with binary strings instead of converting them to integers. Simulating operations step by step is often more memory-efficient. This approach works even for very long binary strings (up to 500 bits in this problem). Coding challenges like this are a great way to sharpen algorithmic thinking! 🧠 #Python #CodingChallenge #BinaryNumbers #ProblemSolving #LeetCode #Algorithms
To view or add a comment, sign in
-
-
🚀 Coding Practice — 696. Count Binary Substrings Today I worked on an interesting string problem that tests pattern observation and grouping logic. 🧠 Problem Statement Given a binary string s, count the number of non-empty substrings where: ✔️ The number of 0s and 1s are equal ✔️ All 0s are grouped together ✔️ All 1s are grouped together Example: Input: "00110011" Output: 6 Valid substrings: "0011", "01", "1100", "10", "0011", "01" 💡 Key Insight Instead of checking all substrings (which would be inefficient ❌), we observe: 👉 The string can be divided into consecutive groups of 0’s and 1’s. 👉 For every pair of adjacent groups, the number of valid substrings is: min(length_of_previous_group, length_of_current_group) Why? Because a valid substring can only be formed between two adjacent groups. 🔍 Example Breakdown For "00110011" Groups: 00 → 2 11 → 2 00 → 2 11 → 2 Now calculate: min(2,2) + min(2,2) + min(2,2) = 2 + 2 + 2 = 6 ✅ Final Answer = 6 🧑💻 Python Implementation class Solution(object): def countBinarySubstrings(self, s): prev_group = 0 curr_group = 1 result = 0 for i in range(1, len(s)): if s[i] == s[i - 1]: curr_group += 1 else: result += min(prev_group, curr_group) prev_group = curr_group curr_group = 1 result += min(prev_group, curr_group) return result ⏱ Complexity Analysis Time Complexity: O(n) Space Complexity: O(1) Efficient, clean, and optimal 💯 🔥 What I Learned Pattern recognition is powerful in string problems Group counting can replace brute force substring checking Observing structure reduces complexity from O(n²) → O(n) #Python #DataStructures #Algorithms #CodingPractice #LeetCode #SoftwareEngineering #ProblemSolving #TechJourney
To view or add a comment, sign in
-
-
Nice 🔥 Solving LeetCode – Roman to Integer is a solid fundamentals problem! Here’s a clean LinkedIn description you can post: 🚀 Solved “Roman to Integer” on LeetCode Today I solved the Roman to Integer problem on LeetCode using Python 🔹 Strengthened my understanding of: Hash maps (dictionaries) Reverse traversal technique Handling subtraction cases in Roman numerals Writing clean and optimized logic Implemented an efficient solution by iterating from right to left and managing previous values smartly to handle special cases like IV, IX, XL, etc. Consistency in solving problems is improving my logical thinking day by day 💪 #LeetCode #Python #ProblemSolving #DataStructures #CodingJourney #100DaysOfCodeNice 🔥 Solving LeetCode – Roman to Integer is a solid fundamentals problem! Here’s a clean LinkedIn description you can post: 🚀 Solved “Roman to Integer” on LeetCode Today I solved the Roman to Integer problem on LeetCode using Python 🐍 🔹 Strengthened my understanding of: Hash maps (dictionaries) Reverse traversal technique Handling subtraction cases in Roman numerals Writing clean and optimized logic Implemented an efficient solution by iterating from right to left and managing previous values smartly to handle special cases like IV, IX, XL, etc. Consistency in solving problems is improving my logical thinking day by day #LeetCode #Python #ProblemSolving #DataStructures #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
Day 4 of Python was a masterclass in decision-making. I stopped writing "scripts" and started writing "logic flows." Here’s what I learned about building a resilient program: 🔹 The Power of the 'If': From simple one-way decisions to complex Nested and Multi-way (elif) structures. It’s not just about "Yes or No"; it’s about mapping out every possible fog in the road. 🔹 Indentation is Architecture: In Python, a few spaces aren't just for clean looks—they are the law. Indentation tells the computer exactly which code belongs to which decision. If your alignment is off, your logic is off. 🔹 The (Try/Except): I learned how to anticipate human error. Instead of letting the program crash when a user enters a string instead of a number, I used try/except to catch the mistake gracefully and keep the engine running. I’m training my brain to remember that = assigns a value, but == asks a question. I am slowly getting there 🙂 Day 5 is moving into the world of Functions and Iterations (Loops). I’m shifting from making decisions to automating repetitive tasks. The pieces are finally starting to click together. #Python #CodingLogic #BuildInPublic #SoftwareDevelopment #TechJourney #ProblemSolving
To view or add a comment, sign in
-
-
Building logic in Python isn’t always as simple as it looks. This visual captures a moment every developer has experienced — staring at a screen full of if, elif, else, and boolean conditions, wondering why something that seemed so clear in your head suddenly feels tangled. On one side, you see the chaos: overlapping thoughts, scattered conditions, and that familiar “Where did this go wrong?” moment. On the other side, there’s structure — a clean flowchart that reminds us that good logic isn’t about writing more code, but about thinking clearly before we write it. The contrast tells a powerful story: messy logic isn’t a lack of skill — it’s usually a lack of structure. Once we break problems down step-by-step and map decisions properly, everything starts to make sense. Every programmer moves from confusion to clarity. The key is slowing down, visualizing the flow, and trusting the process. If you’ve ever struggled with conditional statements or boolean logic in Python, you’re not alone — it’s part of the journey toward becoming a better problem solver. #DataAnalystLearningJourney
To view or add a comment, sign in
-
More from this author
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development