Check if Number is Power of Two Using Recursion

💡 A Simple Recursive Way to Check Power of Two Today I revisited a basic but interesting problem: Check if a number is a power of two. Instead of jumping straight to bit manipulation, I tried solving it using recursion — and it turned out to be a neat approach. 🔁 Idea: A number is a power of 2 if: It keeps dividing cleanly by 2 And eventually becomes 1 ⚙️ Approach: If n == 1 → ✅ True If n <= 0 or n is odd → ❌ False Otherwise → recursively check n // 2 ✨ What I liked about this: Very intuitive Mirrors the mathematical definition Easy to understand and implement 📊 Complexity: Time: O(log n) Space: O(log n) due to recursion stack 🧠 Takeaway: Sometimes, going back to the mathematical intuition behind a problem leads to the simplest solution. Of course, there’s also a more optimized bit manipulation trick: 👉 n & (n - 1) == 0 But recursion helps in building strong fundamentals. python code https://lnkd.in/giwyBUiQ How would you approach this — recursion or bit manipulation? 👇 #Algorithms #Recursion #Python #CodingInterview #ProblemSolving #LeetCode Rajan Arora

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories