← Math

Power of Two

Easy
Python
def is_power_of_two(n):
    return n>0 and (n&(n-1))==0
Java
public boolean isPowerOfTwo(int n){
    return n>0&&(n&(n-1))==0;
}

Key Insight

Power of 2 has one bit set. n&(n-1) clears it. Nearly identical.

Python → Java Differences

  • Bit trick identical
  • 'and' vs '&&'
  • Nearly identical solutions
Python
def is_power_of_two(n):
    return n>0 and (n&(n-1))==0
Java
public boolean isPowerOfTwo(int n){
    return n>0&&(n&(n-1))==0;
}

Algorithm Steps

1. Positive and one bit set
2. n&(n-1) clears lowest bit