Power of Four
Decide whether an integer is a power of four by checking its bits, with no loop.
Given an integer n
Example 1
Output: true
Example 2
Output: false
Example 3
Output: true
Explanation: 40 = 1.
The Idea
Start with 1 and keep multiplying by 4: 1, 4, 16, 64, 256, and so on. Those are the powers of four. Example 1 asks about 16, which is on that list as 4 × 4, so the answer is true. Example 2 asks about 5, which falls between 4 and 16, so the answer is false.
One way to decide is to divide by 4 for as long as nothing is left over, then see whether 1 remains. Dividing 16 gives 4, then 1, so 16 is a power of four. That takes a loop, though. Could we tell just by looking at the number once?
We can, if we look at it the way Java stores it. A Java int
Multiplying by 4 moves every bit two positions to the left, much as multiplying by 100 adds two zeros to an ordinary number. Starting from 1, whose bit is at position 0, the single 1 jumps to position 2 for 4, then to position 4 for 16. The picture below shows these numbers next to their neighbours 2 and 8.
In the rows labelled n = 1, n = 4 and n = 16, the single 1 is teal and sits at position 0, 2 or 4, in the shaded columns. The rows labelled n = 2 and n = 8 also have one 1 bit, but it is orange and sits at the odd positions 1 and 3. Those two numbers are powers of two, and not powers of four.
So a power of four is a positive number with exactly one 1 bit, and that bit is at an even position. The one-bit part and the even-position part can each be checked with one or two operations, and no loop. The bottom row of the picture, labelled mask, is the tool for the even-position part.
Solution Approach
Besides the loop that divides by 4, there is a way with no loop, made of three checks: n has exactly one 1 bit, that bit is at an even position, and n is above 0. A remainder test can also stand in for the second check.
Dividing by four in a loop
Is the loop really a problem? Not much. The largest power of four that fits in an int
Exactly one 1 bit
How can we tell that n has a single 1 bit? Subtract 1 and look at what changes. In 16, written 10000, the 1 at position 4 becomes 0 and every bit below it becomes 1, so 15 is 01111. Java's &16 & 15
Now try 5 from Example 2. It is 101, and 5 - 1 = 4 is 100. Subtracting 1 changed only the lowest 1, so the 1 at position 2 is still in both numbers, and 5 & 4(n & (n - 1)) == 0
A 1 bit at an even position
Which numbers with one 1 bit have it at an even position? The mask from the picture answers it. A mask is a fixed number whose 1 bits mark the positions we want to look at. Here it is 0x55555555
Eight 5s give 32 bits, 0101…0101, with a 1 at positions 0, 2, 4 and so on up to 30. The AND n & 0x55555555
Zero and negative numbers
What about 0 and negative numbers? None of them is a power of four, because 4k is at least 1. Java stores a negative int
One negative number has a single 1 bit: Integer.MIN_VALUEintn > 0&&
Strictly, the other two checks already reject 0 and Integer.MIN_VALUEintn > 0
Another way to check the position (optional)
Among the numbers with one 1 bit, the powers of four leave a remainder of 1 when divided by 3: 1, 4, 16, 64. The others, 2, 8, 32 and so on, leave 2. That is because 4 is 3 + 1, so multiplying by 4 keeps the remainder the same. So n % 3 == 1int
Java Solution
The method isPowerOfFour&&
- First, check
, so 0 and every negative number return false straight away.n > 0 - Next, check
, which holds only when n has exactly one 1 bit.(n & (n - 1)) == 0 - Last, AND n with the mask, kept in a constant named
with the valueEVEN_POSITIONS . A result other than 0 means the single 1 bit is at an even position, and the method returns true.0x55555555
The mainInteger.toBinaryStringintint
import java.util.ArrayList;
import java.util.List;
public class PowerOfFour {
private static final int EVEN_POSITIONS = 0x55555555; // 1 bits at positions 0, 2, ..., 30
public static boolean isPowerOfFour(int n) {
return n > 0 // rules out 0 and negative numbers
&& (n & (n - 1)) == 0 // exactly one 1 bit
&& (n & EVEN_POSITIONS) != 0; // and that bit is at an even position
}
public static void main(String[] args) {
int[] tests = {16, 5, 1, 8, 0, -16, 1073741824, Integer.MAX_VALUE, Integer.MIN_VALUE};
for (int n : tests) {
String bits = Integer.toBinaryString(n);
System.out.printf("%11d %32s %b%n", n, bits, isPowerOfFour(n));
}
List<Integer> passing = new ArrayList<>();
for (int position = 0; position < 32; position++) {
if (isPowerOfFour(1 << position)) {
passing.add(position);
}
}
System.out.println("single 1 bit at these positions passes: " + passing);
}
}
Running it prints:
16 10000 true
5 101 false
1 1 true
8 1000 false
0 0 false
-16 11111111111111111111111111110000 false
1073741824 1000000000000000000000000000000 true
2147483647 1111111111111111111111111111111 false
-2147483648 10000000000000000000000000000000 false
single 1 bit at these positions passes: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30]
For 16, 5 and 1 the method prints true, false and true, matching the three examples. The line for 8 shows 1000, a single 1 at position 3, and prints false, so the mask check turns it away. The inputs 0 and -16 print false as well, and -16 shows all 32 bits, starting with 28 ones.
The number 1073741824 is 415, a 1 followed by 30 zeros, and it prints true. The value 2147483647, the largest intInteger.MIN_VALUEn > 0
The last line lists the positions where a single 1 bit passes: 0, 2, 4 and so on up to 30. That is 16 positions, one for each power of four from 40 to 415.
Complexity
The method makes three checks on one int
- Time: O(1), because every n costs one comparison, one subtraction and two ANDs, with no loop, while the division loop needs one pass per factor of 4 in n, up to 15.
- Space: O(1), because the method keeps nothing but n and the constant mask.
Base 3 has no bit pattern like this; see