30:00
Given a positive integer n, check whether it has alternating bits: every two adjacent bits in its binary representation must have different values.
1≤n≤231−11 \leq n \leq 2^{31} - 11≤n≤231−1
Run code to see results.
n = 5 is 101 in binary. Alternating means every bit differs from its left neighbour.
compare every bit with its left neighbour
n = 5
x bit = n bit ^ neighbour
red 0 in x = two equal neighbours
x all ones ⇔ x & (x+1) = 0
Given a positive integer n, decide whether its binary form alternates, so that no two neighbouring bits are equal. For example 5 (101) alternates and 7 (111) does not.