Power of Four

Decide whether an integer is a power of four by checking its bits, with no loop.

Given an integer n, return true if it is a power of four and false otherwise. A power of four is 4 multiplied by itself some number of times, n = 4k for a whole number k ≥ 0, so 1 = 40 counts too.

Example 1
Input: n = 16
Output: true
Example 2
Input: n = 5
Output: false
Example 3
Input: n = 1
Output: true
Explanation: 40 = 1.
Solution

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 is a row of 32 bits, each 0 or 1. Positions are counted from 0 on the right, and each position is worth twice the one to its right: position 0 is worth 1, position 2 is worth 4, and position 4 is worth 16. So 16 is written 10000, a single 1 at position 4.

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.

The numbers 1, 2, 4, 8 and 16 in binary, each with a single 1 bit. For the powers of four 1, 4 and 16 the bit is at an even position, 0, 2 or 4. For 2 and 8 it is at an odd position, 1 or 3. The mask 0x55555555 has a 1 at every even position.

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 is 415 = 1,073,741,824, so the loop divides at most 15 times. Its work still grows with the size of n, while the checks on the bits take the same few steps for every n.

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 & operator, called AND, lines 16 and 15 up bit by bit and keeps a 1 only where both have one. There is no such position here, so 16 & 15 is 0.

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 is 4, not 0. Any positive number with two or more 1 bits keeps its highest 1 in the same way. So (n & (n - 1)) == 0 holds exactly when n has one 1 bit, which is the whole test on the Power of Two page.

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, written in hexadecimal, where each digit stands for four bits and the digit 5 stands for 0101.

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 keeps only the bits of n at those even positions. For 16 it keeps the 1 at position 4 and gives 16. For 8, whose 1 is at position 3, it gives 0. Without this check, 8 and 2 would both pass, since each has a single 1 bit.

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 in two's complement, the form in which -16 is written as 28 ones followed by 0000. The bit at position 31 is 1 for every negative number.

One negative number has a single 1 bit: Integer.MIN_VALUE, -2,147,483,648, which is a 1 at position 31 and zeros everywhere else. For it, n - 1 would wrap around to 2,147,483,647, the largest int. Putting n > 0 first and joining the checks with &&, which skips the rest once one check is false, rejects 0 and all negative numbers before n - 1 is computed. For a positive n, n - 1 is never below 0, so it cannot wrap.

Strictly, the other two checks already reject 0 and Integer.MIN_VALUE, since neither has a 1 at an even position. A run over all 232 int values gave the same answers with and without n > 0. Keeping it states the rule plainly and keeps the subtraction away from the wraparound.

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 == 1 can replace the mask, and a run over all int values gave the same answers as the mask version.

Java Solution

The method isPowerOfFour makes three checks, joined with &&, so it stops at the first one that fails:

  1. First, check n > 0, so 0 and every negative number return false straight away.
  2. Next, check (n & (n - 1)) == 0, which holds only when n has exactly one 1 bit.
  3. Last, AND n with the mask, kept in a constant named EVEN_POSITIONS with the value 0x55555555. A result other than 0 means the single 1 bit is at an even position, and the method returns true.

The main method prints each test number with its bits, from Integer.toBinaryString (which leaves out leading zeros), and the result. It tries the three examples, 8, 0, -16, the largest power of four in an int and both ends of the int range, then a single 1 bit at each of the 32 positions.

Java
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:

Output
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 int, has 31 ones and fails the one-bit check. At the other end, -2147483648 is Integer.MIN_VALUE, a lone 1 at position 31, and prints false because n > 0 stops it before n - 1 is worked out.

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, whatever its value.

  • 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 Power of Three.