Skip to content
Problem 693 · LeetCode 693(opens in a new tab)

Binary Number with Alternating Bits

EasyBit manipulation

You are given a positive integer n. Look at it written in binary, without leading zeros.

Return true if every pair of neighbouring bits is different, so the bits go 1, 0, 1, 0 and so on. Return false if any two neighbouring bits are equal.

Example 1

Input:  n = 21
Output: true
Why:    21 is 10101 in binary; no two neighbours match
2 more examples and the constraints

Example 2

Input:  n = 13
Output: false
Why:    13 is 1101; the two leading 1s are neighbours

Example 3

Input:  n = 10
Output: true
Why:    10 is 1010; it alternates all the way

Constraints

  • 1 ≤ n ≤ 2,147,483,647 (2³¹ − 1)

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Compare bits one by oneO(log n)
  2. XOR with a shifted copyO(1)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for a 31-bit nVerdict
Compare bits one by oneO(log n)
Fine; a loop of at most 31 turns
XOR with a shifted copyO(1)
Best; four operations, no loop

n = the input number; log n is its bit count.

Edge cases to test

  • n = 1. A single bit has no neighbours, so the answer is true.
  • n = 2. Binary 10 alternates: true. And n = 3 (11) is false.
  • The largest alternating number. 1,431,655,765 is 31 alternating bits; x + 1 overflows a 32-bit int, so use a 64-bit type.
  • All ones. 2,147,483,647 has 31 ones in a row: false on the first comparison.

Common mistakes

  • Testing x & (x + 1) on n itself instead of on n XOR (n >> 1).
  • Computing x + 1 in a 32-bit signed int in C++, where the overflow is undefined behaviour.
  • Forgetting parentheses in Java or C++: x & x + 1 == 0 parses as x & ((x + 1) == 0).

How to talk through it

  1. 1Clarify. Is n always positive? Do leading zeros count? (No: only the bits up to the highest 1.)
  2. 2Give the loop. Shift right, compare each bit with the one before it: at most 31 turns.
  3. 3Find the trick. XOR with n >> 1 marks every pair that differs, so alternating means all ones.
  4. 4Test all ones. x & (x + 1) is 0 only for a block of ones, because the carry runs through it.
  5. 5Test out loud. Try 1, 3, 10 and 1,431,655,765, where x + 1 needs 64 bits.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?