Check if Number Has Alternating Binary Bits

🚀 Coding Practice — Check if a Number Has Alternating Bits (Bit Manipulation) 🔄✨Alternating Bits ⚡ The Binary Seesaw 🔥🔥🔥 Beats 100% Today I worked on a neat bit-manipulation problem: determine whether a number’s binary representation contains alternating bits — meaning no two adjacent bits are the same. Examples: ✅ Valid → 10101, 0101 ❌ Invalid → 110, 1001 🧠 Intuition Think of binary digits like stepping stones that must alternate colors — ⚫⚪⚫⚪ — at every step. If you ever step on two same-colored stones in a row, the pattern breaks. Instead of converting the number to a binary string, we directly inspect each bit using bitwise operations — which is faster and more memory-efficient. Core idea: Extract the last bit using n & 1 Shift right using n >> 1 Compare with the previous bit If equal → not alternating 🛠️ Approach (Step-by-Step) 1️⃣ Capture the least significant bit (LSB) using n & 1 2️⃣ Right shift the number to move to the next bit 3️⃣ Loop while the number is not zero: Store previous bit Extract current bit If both are equal → return False Otherwise continue shifting 4️⃣ If loop completes → all bits alternated → return True 💻 Python Code class Solution:     def hasAlternatingBits(self, n: int) -> bool:         curr = n & 1         n >>= 1         while n:             prev = curr             curr = n & 1             if curr == prev:                 return False             n >>= 1         return True 📊 Complexity Analysis ✅ Time Complexity: O(log n) We check each bit once. A number has about log₂(n) bits. ✅ Space Complexity: O(1) Only constant variables are used. ✨ Bit manipulation problems like this are great for strengthening low-level logic and understanding how numbers are stored internally. Small problems — big thinking benefits. #Python #CodingPractice #BitManipulation #DSA #ProblemSolving #InterviewPrep #LearnToCode #TechLearning

  • graphical user interface, text

To view or add a comment, sign in

Explore content categories