Alternating Bits in Binary Representation

🔥 Day 508 of #750DaysOfCode 📌 Problem: Binary Number with Alternating Bits (LeetCode 693) Today’s challenge was to determine whether a given positive integer has alternating bits in its binary representation. 👉 A number has alternating bits if no two adjacent bits are the same. 🧠 Example: 5 → 101 ✅ (Alternating → True) 7 → 111 ❌ (Not alternating → False) 11 → 1011 ❌ (Last two bits same → False) 💡 Key Insight If a number has alternating bits: XOR it with itself right-shifted by 1 The result should be all 1s A number with all 1s has the property: 🔎 Why This Works? Example: n = 5 → 101 n = 101 n >> 1 = 010 XOR = 111 Now check: 111 & 1000 = 0 Hence ✅ True. ⏱ Time Complexity: O(1) 📦 Space Complexity: O(1) Day 508 completed. Still building consistency. Still sharpening problem-solving. 💪 On to Day 509 🚀 #750DaysOfCode #Day508 #LeetCode #Java #DSA #BitManipulation #ProblemSolving #CodingJourney #Consistency #TechGrowth

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories