Are bits alternating in integer using JavaScript?

We are required to write a JavaScript function that takes in an integer, num, as the first and the only argument.

Our function should check whether the binary representation of num has alternating bits − namely, if two adjacent bits will always have different values.

For example, if the input to the function is 5, the output should be true because the binary form of 5 is 101 which has alternating bits (1-0-1).

Understanding Alternating Bits

Alternating bits mean that no two adjacent bits in the binary representation are the same. For instance:

  • 5 ? 101 ? alternating (true)
  • 10 ? 1010 ? alternating (true)
  • 7 ? 111 ? not alternating (false)
  • 11 ? 1011 ? not alternating (false)

Using String Conversion Method

The first approach converts the number to binary string and checks each adjacent pair:

const isAlternating = (num = 1) => {
    const binary = num.toString(2);
    let curr = binary[0];
    for(let i = 1; i < binary.length; i++){
        const el = binary[i];
        if(curr !== el){
            curr = el;
            continue;
        };
        return false;
    };
    return true;
};

// Test cases
console.log(isAlternating(5));   // 101 ? alternating
console.log(isAlternating(10));  // 1010 ? alternating
console.log(isAlternating(7));   // 111 ? not alternating
console.log(isAlternating(11));  // 1011 ? not alternating
true
true
false
false

Using Bitwise Operations (Optimized)

A more efficient approach uses bitwise operations to check alternating patterns without string conversion:

const isAlternatingBitwise = (num) => {
    // XOR with right-shifted version creates all 1s if alternating
    const xor = num ^ (num >> 1);
    
    // Check if xor + 1 is a power of 2 (all bits set)
    return (xor & (xor + 1)) === 0;
};

// Test cases
console.log(isAlternatingBitwise(5));   // 101
console.log(isAlternatingBitwise(10));  // 1010
console.log(isAlternatingBitwise(7));   // 111
console.log(isAlternatingBitwise(11));  // 1011
true
true
false
false

How the Bitwise Method Works

For alternating bits, XOR with the right-shifted version produces all 1s:

  • 5 = 101, 5 >> 1 = 10, 101 ^ 010 = 111
  • 7 + 1 = 8 = 1000, 111 & 1000 = 0 ? alternating

Comparison

Method Time Complexity Space Complexity Readability
String Conversion O(log n) O(log n) High
Bitwise Operations O(1) O(1) Medium

Conclusion

Both methods effectively check for alternating bits. Use string conversion for clarity or bitwise operations for optimal performance. The bitwise approach is more efficient with constant time and space complexity.

Updated on: 2026-03-15T23:19:00+05:30

229 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements