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
- −2³¹ ≤ n ≤ 2³¹ − 1
Edge cases to test
- n = 0 and negative n:
false - n = 1 (2⁰)
n = −2³¹(one bit set, but negative)
Follow-up questions
- How do you test a power of four?
- A power of two whose single bit is at an even position:
n & 0x55555555is 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) == 0C++
#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
- Rotate Image (Medium)
- Spiral Matrix (Medium)
- Set Matrix Zeroes (Medium)
- Search a 2D Matrix (Medium)
- Search a 2D Matrix II (Medium)
- Valid Sudoku (Medium)
- Single Number (Easy)
- Single Number II (Medium)
- Single Number III (Medium)
- Number of 1 Bits (Easy)
- Counting Bits (Easy)
- Reverse Bits (Easy)
- Missing Number (Easy)
- Sum of Two Integers (Medium)