PPractick

DSA interview question

Check Whether a Number Is a Power of Two

Easy · Algorithms · Topics: bit manipulation

The problem

A memory allocator only accepts block sizes that are powers of two (1, 2, 4, 8, …), because it splits and merges blocks by halving and doubling. Every allocation request must be validated instantly. A power of two has exactly one set bit, and subtracting 1 flips that bit off and turns every lower bit on, so n & (n − 1) is zero exactly for powers of two. Zero and negative numbers must be rejected separately.

Example: 16 → true; 3 → false; 0 → false.

Function signature

bool isPowerOfTwo(int n);

Test cases

InputOutputExplanation
1true2⁰
16true10000
3false11 has two set bits
0falseNo set bits
-16falseNegative numbers are never powers of two
1073741824true2³⁰, the largest in a 32-bit int

(Confirm: n is a 32-bit signed integer; only positive powers of two, 2⁰ to 2³⁰, return true.)

How interviewers phrase it

Clarifying questions to ask

  1. Is 1 (2⁰) a power of two? (Yes.)
  2. Can n be zero or negative? (Yes, and they return false.)
  3. Are loops allowed?

Follow-ups to expect

  1. "Why does n & (n − 1) work?"
  2. "Why check n > 0?"
  3. "Another bit trick?"
  4. "How would you test for a power of four?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in