Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Check whether a number is a power of four with bit tricks.

Problem: Check whether a number is a power of four with bit tricks.
def p4(n):
    return n > 0 and n & (n - 1) == 0 and n & 0x55555555 != 0
print([p4(x) for x in (16, 32, 64, 1, 0)])
What is printed?
  1. A. [True, True, True, True, False]
  2. B. [True, False, True, False, False]
  3. C. [True, False, True, True, False]
  4. D. [True, False, True, True, True]

Correct answer: C. [True, False, True, True, False]

n & (n − 1) == 0 keeps powers of two; the mask 0x55555555 has 1s only at even bit positions (0, 2, 4, …), where powers of four live. 32 = 2⁵ has its bit at an odd position, so it fails; 1 = 4⁰ passes; 0 fails the n > 0 test.

More Coding Interview Problems questions

Exams that ask this topic