Power of Two

easy math bit manipulation recursion

Problem

Given an integer n, return true if and only if it is a power of two.

Inputn = 16
Outputtrue
A power of two has exactly one set bit. Subtracting 1 flips that bit and all bits below it, so n & (n − 1) clears it — and the result is 0 only when there was exactly one bit. Guard against n ≤ 0.

def is_power_of_two(n):
    return n > 0 and (n & (n - 1)) == 0
function isPowerOfTwo(n) {
  return n > 0 && (n & (n - 1)) === 0;
}
class Solution {
    public boolean isPowerOfTwo(int n) {
        return n > 0 && (n & (n - 1)) == 0;
    }
}
bool isPowerOfTwo(int n) {
    return n > 0 && (n & (n - 1)) == 0;
}
Time: O(1) Space: O(1)