Power of Two
Decide whether an int is a power of two with one bit test and no loop.
Given an integer ntruefalse
Example 1
Output: true
Explanation: 20 = 1.
Example 2
Output: true
Explanation: 24 = 16.
Example 3
Output: false
The Idea
Start at 1 and keep doubling: 1, 2, 4, 8, 16, 32. Those are the powers of two, and 16 from Example 2 is among them. By hand, you would check a number by halving it until you reach 1 or get stuck on an odd number. The 3 from Example 3 is odd straight away, so it is not a power of two.
A computer sees n100001100
Doubling a number moves every bit one position to the left. Starting from 1, which is a single 1 at position 0, every power of two is therefore one 1 followed by zeros. So the question becomes: does n
Subtracting 1 helps here. In decimal, 1000 - 1 = 999: the borrow turns the last nonzero digit down and every 0 to its right into 9. Binary works the same way. Subtracting 1 turns the lowest 1 bit into 0 and every 0 to its right into 1, and leaves the bits to its left alone.
Then compare nn - 1n & (n - 1)
On the left, 16 has its single 1 bit at position 4. In the row labelled 15 = 16 - 116 & 15
On the right, 12 has two 1 bits. Subtracting 1 flips only positions 2, 1 and 0, so the 1 at position 3 is in both rows. The row labelled 12 & 1101000
So n & (n - 1)nn
Solution Approach
The bit test replaces a halving loop, and with it the code comes down to two decisions: how to write the test in Java, and how to handle 0 and negative numbers. Other one-line tests are an optional extra.
Halving in a loop
What would the plain way look like? Divide nint
Writing the bit test
How does the picture's check look in Java? It is (n & (n - 1)) == 0&&&truefalse
Zero and negative numbers
Which inputs fool the bit test? Every Java intint
Now try 0. It has no 1 bits, and 0 - 1 is -1, whose 32 bits are all 1. 0 & -1Integer.MIN_VALUE
No power of two is 0 or negative, so the method checks n > 0&&truefalse
Other one-line tests
Are there other ways to say "positive with one 1 bit"? In a test run on 0, -16, Integer.MIN_VALUEint
- The test
counts the 1 bits directly.n > 0 && Integer.bitCount(n) == 1 - The test
usesn > 0 && (n & -n) == n , which keeps only the lowest 1 bit: for 12 it gives 4. A number with one 1 bit stays the same.n & -nSingle Number III explains why works.n & -n - The test
relies on 230, the largest power of two in ann > 0 && (1 << 30) % n == 0 , whose only divisors are smaller powers of two.int
Taking a logarithm is not safe. Math.log(1 << 29) / Math.log(2)
Java Solution
The method isPowerOfTworeturn
- First, check
. If it fails,n > 0 stops there and the method returns&& .false - Compute
, which turns the lowest 1 bit ofn - 1 into 0 and the zeros to its right into 1s.n - AND it with
and return whether the result is 0, which meansn had a single 1 bit.n
The mainshowInteger.toBinaryStringisPowerOfTwointInteger.MIN_VALUE
public class PowerOfTwo {
public static boolean isPowerOfTwo(int n) {
// positive, and n - 1 turns the single 1 bit off, leaving no 1 bit in common
return n > 0 && (n & (n - 1)) == 0;
}
static void show(int n) {
String bits = Integer.toBinaryString(n);
boolean bitTest = (n & (n - 1)) == 0;
System.out.printf("%11d %32s bit test: %-5b answer: %b%n",
n, bits, bitTest, isPowerOfTwo(n));
}
public static void main(String[] args) {
show(1);
show(16);
show(3);
show(12);
show(1 << 30);
show(Integer.MAX_VALUE);
show(0);
show(-16);
show(Integer.MIN_VALUE);
}
}
Running it prints:
1 1 bit test: true answer: true
16 10000 bit test: true answer: true
3 11 bit test: false answer: false
12 1100 bit test: false answer: false
1073741824 1000000000000000000000000000000 bit test: true answer: true
2147483647 1111111111111111111111111111111 bit test: false answer: false
0 0 bit test: true answer: false
-16 11111111111111111111111111110000 bit test: false answer: false
-2147483648 10000000000000000000000000000000 bit test: true answer: false
Integer.toBinaryString1000011truefalse
Look at the line for 0: the bit test alone says truen > 0false
The inner parentheses in (n & (n - 1)) == 0==&n > 0 && n & (n - 1) == 0n & ((n - 1) == 0)intboolean
Complexity
The method does the same few operations on one int
- Time: O(1), because it does one comparison, one subtraction and one AND, with no loop over the 32 bits of
.n - Space: O(1), because it keeps nothing besides the value of
for the moment of the AND.n - 1