Ashish Tiwari’s Post

Day 10 of Java DSA Journey 🚀 📌 Problem: Power of Two (LeetCode 231) Most people solve this using loops: ➡️ Keep dividing by 2 until you reach 1 But today I learned something better: 👉 You can solve it in ONE line using bit manipulation 🤯 💡 Core Idea A number is a power of two if: ✔️ It has only one ‘1’ in its binary form Examples: 1 → 0001 2 → 0010 4 → 0100 16 → 10000 🧠 The Magic Trick 👉 n & (n - 1) This removes the rightmost set bit So: If result = 0 → only one bit was set → ✅ Power of Two Else → ❌ Not a power of two ⚡ Complexity ⏱ Time: O(1) 📦 Space: O(1) 🔥 Pro Tips (Interview Level) 💡 Tip 1: Always Check Positivity First n > 0 is mandatory — bit tricks fail for negative numbers. 💡 Tip 2: Understand, Don’t Memorize n - 1 flips: the rightmost 1 → 0 all bits after it → 1 That’s why the trick works. 💡 Tip 3: This Pattern Appears Everywhere The same trick is used in: Counting set bits Subset generation Low-level optimizations 👉 Learn it once, reuse forever. 💡 Tip 4: Alternative Trick (Even Cleaner) Another way: 👉 (n & -n) == n This isolates the lowest set bit. If it's equal to n, only one bit exists. 💡 Tip 5: Bitwise = Senior-Level Thinking Using bit manipulation shows: ✔️ You understand how data is stored ✔️ You can optimize beyond brute force 🔥 Real Insight This problem is not about checking powers… It’s about recognizing: 👉 Patterns in binary representation Once you see that, the solution becomes obvious. Consistency builds mastery 🔑 #DSA #LeetCode #Java #BitManipulation #CodingJourney #ProblemSolving #InterviewPrep #Day10 #BitManipulation #InterviewPrep #CleanCode #Array #Optimization #MCA #lnct #100DaysOfCode #SoftwareEngineering #Algorithms #InPlaceAlgorithms #TechLearning #JavaDeveloper

  • graphical user interface

To view or add a comment, sign in

Explore content categories