Alternating Bit

Implement hasAlternatingBits

Given a positive integer n, determine whether its binary representation has strictly alternating bits — no two adjacent bits are ever the same. Comparing each bit to the one before it works directly, but there's a shortcut: XOR-ing n with itself shifted right by one bit turns every "differs from its neighbor" position into a 1. If the original bits truly alternated everywhere, that XOR result is a solid run of 1s from the lowest bit up — a pattern that AND-ed with its own successor (x & (x + 1)) collapses to 0, the same identity used earlier to test for an all-ones run.

Example 1:

Input: n = 5

Output: true

Example 2:

Input: n = 7

Output: false

Example 3:

Input: n = 10

Output: true

+ 7 hidden test cases run on Submit.

Constraints:

  • 1 ≤ n ≤ 2³¹ − 1

n =

5