Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern

Problem: Check whether a number is a power of two and isolate its lowest set bit.

Problem: Check whether a number is a power of two and isolate its lowest set bit.
print("; ".join(f"{x > 0 and x & (x - 1) == 0} {x & -x}" for x in (64, 96, 0, 1)))
What is printed?
  1. A. True 64; False 32; False 0; True 1
  2. B. True 64; True 32; True 0; True 1
  3. C. True 64; False 32; True 0; True 1
  4. D. True 64; False 64; False 0; True 1

Correct answer: A. True 64; False 32; False 0; True 1

x & (x − 1) clears the lowest set bit, so it is 0 only when x has a single set bit – the x > 0 guard rules out 0. x & −x isolates the lowest set bit using two's complement: 96 = 1100000₂ → 32. O(1).

More Coding Interview Problems questions

Exams that ask this topic