Skip to main content
PreparationZone Logo
PreparationZone
Back to Coding

Coding · Easy · Free

Check if a number is a power of two

CodingBit ManipulationFresher
Model answer

Approach

  • A power of two has exactly one set bit.
  • Use n > 0 && (n & (n-1)) == 0.

Java Solution

Java
boolean isPowerOfTwo(int n) {
    return n > 0 && (n & (n - 1)) == 0;
}
Complexity
TimeO(1)
SpaceO(1)
Interview tip: Explain why n & (n-1) clears the lowest set bit.