Binary Number with Alternating Bits

Given a positive integer n, check whether it has alternating bits: every two adjacent bits in its binary representation must have different values.

30:00

Binary Number with Alternating Bits
easy
Free written solution
Topics
Companies

Given a positive integer n, check whether it has alternating bits: every two adjacent bits in its binary representation must have different values.

Example 1:
Input: {"n":5}
Output: true
Constraints:
  • 1≤n≤231−11 \leq n \leq 2^{31} - 1

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"n":5}

n = 5 is 101 in binary. Alternating means every bit differs from its left neighbour.

compare every bit with its left neighbour

n = 5

n
1
0
1
n >> 1
0
1
0
x
·
·
·
x + 1
x & (x+1)
3
2
1
0

x bit = n bit ^ neighbour

red 0 in x = two equal neighbours

x all ones ⇔ x & (x+1) = 0

Variables
VariableValue
n5
binary101
DepthFunction Call
Stack empty
0/8