Binary Number with Alternating Bits

Given a positive integer n, check whether it has alternating bits: namely, whether every pair of adjacent bits in its binary representation always has different values.

Return true if n has alternating bits, otherwise return false.

Example 1
Inputn = 5
Outputtrue
The binary representation of 5 is 101, whose adjacent bits are all different.
Example 2
Inputn = 7
Outputfalse
The binary representation of 7 is 111, which has adjacent bits with the same value.

Constraints

  • 1 <= n <= 2^31 - 1

Asked at 5 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate