We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Binary Number with Alternating Bits

Number: 693

Difficulty: Easy

Paid? No

Companies: Yahoo


Problem Description

Given a positive integer n, determine whether its binary representation has alternating bits. In other words, check if every pair of adjacent bits is different.


Key Insights

  • A number with alternating bits in binary will have no two consecutive bits that are the same.
  • One efficient approach is to use bit manipulation:
    • Compute x = n XOR (n >> 1). For a number with alternating bits, x will be a sequence of 1's.
    • A sequence of consecutive 1's has the property that x & (x + 1) equals 0.
  • This method avoids converting the integer to a string, keeping the solution efficient.

Space and Time Complexity

Time Complexity: O(1) - the number of operations is constant since the number of bits (at most 31) is fixed.
Space Complexity: O(1) - only a few extra variables are used.


Solution

We solve the problem by using bit manipulation. The steps are as follows:

  1. Perform an XOR between n and n shifted right by 1 bit (n ^ (n >> 1)). This operation highlights transitions between bits.
  2. Check if the resulting number is a sequence of all 1's. A number that is all 1's will satisfy the condition (x & (x + 1) == 0).
  3. If the condition holds, the binary representation of n has alternating bits; otherwise, it does not.

This approach leverages understanding of bit properties and uses basic bitwise operators to achieve the solution in constant time and space.


Code Solutions

# Python solution with inline comments

def hasAlternatingBits(n):
    # XOR n with n shifted right by 1 to capture differences between adjacent bits
    x = n ^ (n >> 1)
    # Check if x is a sequence of 1's by verifying if x & (x + 1) equals 0
    return (x & (x + 1)) == 0

# Test cases
print(hasAlternatingBits(5))   # Expected output: True (binary: 101)
print(hasAlternatingBits(7))   # Expected output: False (binary: 111)
print(hasAlternatingBits(11))  # Expected output: False (binary: 1011)
← Back to All Questions