Skip to main content
PreparationZone Logo
PreparationZone
Back to Fundamentals

Fundamentals · Easy · Free

Check if a number is a power of two using bit manipulation.

FresherFundamentalsData Structures & Algorithms
Model answer

Power of two check

java
boolean isPowerOfTwo(int n) {
  return n > 0 && (n & (n - 1)) == 0;
}

Powers of two have single 1 bit; n-1 flips trailing bits.

Follow-up: next power of two with bit smearing.