Algo-Sim › Matrix & Bit Manipulation

Power of Two

Easy · Matrix & Bit Manipulation · step through it in Java, Python and C++ on your own input

n is a power of two exactly when n > 0 and n & (n − 1) == 0: subtracting 1 clears the lowest set bit, and nothing else may be left.

Problem

Given an integer n, return true if it is a power of two, that is, if n == 2^x for some integer x ≥ 0. Solve it without loops or recursion.

Constraints

Edge cases to test

Follow-up questions

How do you test a power of four?
A power of two whose single bit is at an even position: n & 0x55555555 is non-zero (LC 342).
How do you test a power of three?
No bit trick: check that the largest power of three in range (3¹⁹) is divisible by n.

Solution

Java

public boolean isPowerOfTwo(int n) {
    if (n <= 0) return false;
    // n - 1 flips the lowest 1 bit and every 0 below it.
    return (n & (n - 1)) == 0;
}

Python

def is_power_of_two(n):
    if n <= 0:
        return False
    # n - 1 flips the lowest 1 bit and every 0 below it.
    return n & (n - 1) == 0

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    bool isPowerOfTwo(int n) {
        if (n <= 0) return false;
        // n - 1 flips the lowest 1 bit and every 0 below it.
        return (n & (n - 1)) == 0;
    }
};

More Matrix & Bit Manipulation problems