Power of Two

Decide whether an int is a power of two with one bit test and no loop.

Given an integer n, return true if it is a power of two and false otherwise. A power of two is a number equal to 2x for some whole number x >= 0, such as 1, 2, 4 or 8. Solve it without loops or recursion.

Example 1
Input: n = 1
Output: true
Explanation: 20 = 1.
Example 2
Input: n = 16
Output: true
Explanation: 24 = 16.
Example 3
Input: n = 3
Output: false
Solution

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 n in binary, as a row of digits that are each 0 or 1, called bits. Count the positions from the right, starting at 0. A 1 at position 4 is worth 24 = 16, so 16 is written 10000. 12 is 8 + 4, so it has 1s at positions 3 and 2: 1100.

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 have exactly one 1 bit? And can we tell without looking at its bits one at a time?

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 n with n - 1 using AND. In Java it is written n & (n - 1), and it keeps a 1 only at the positions where both numbers have a 1. Look at the picture below.

Left: 16 is 10000 and 15 is 01111, so 16 AND 15 is 00000. Right: 12 is 01100 and 11 is 01011; only positions 2, 1 and 0 flip, the 1 bit at position 3 survives, and 12 AND 11 is 01000, which is 8.

On the left, 16 has its single 1 bit at position 4. In the row labelled 15 = 16 - 1, that bit and all four bits to its right have flipped, so the two rows share no 1, and the row labelled 16 & 15 is all zeros.

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 & 11 is 01000, which is 8, not 0.

So n & (n - 1) is n with its lowest 1 bit removed. For a positive n it is 0 exactly when that bit was the only one, and a single 1 bit is what every power of two looks like.

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 n by 2 while it is even and see whether it ends at 1. 16 goes 8, 4, 2, 1 and passes, while 12 goes 6, 3 and stops at the odd 3. It works, but it repeats once per halving, up to 30 times for 230, the largest power of two a Java int can hold, and the problem rules out loops.

Writing the bit test

How does the picture's check look in Java? It is (n & (n - 1)) == 0. The single & works on each bit position of two numbers, unlike &&, which joins two true or false answers. The inner parentheses are needed: without them, the line does not compile.

Zero and negative numbers

Which inputs fool the bit test? Every Java int is 32 bits, positions 0 to 31, kept in a format called two's complement. In that format the bit at position 31 is worth -231 instead of +231, so every int with that bit set is negative.

Now try 0. It has no 1 bits, and 0 - 1 is -1, whose 32 bits are all 1. 0 & -1 is 0, so the bit test says yes. Integer.MIN_VALUE, which is -2,147,483,648, is a single 1 at position 31, and it passes the bit test too.

No power of two is 0 or negative, so the method checks n > 0 first. Java's && looks at its right side only when the left side is true, so 0 and negative numbers return false before the bit test runs.

Other one-line tests

Are there other ways to say "positive with one 1 bit"? In a test run on 0, -16, Integer.MIN_VALUE, the largest int and eight numbers from 1 to 230, three more agree with the bit test:

  • The test n > 0 && Integer.bitCount(n) == 1 counts the 1 bits directly.
  • The test n > 0 && (n & -n) == n uses n & -n, which keeps only the lowest 1 bit: for 12 it gives 4. A number with one 1 bit stays the same. Single Number III explains why n & -n works.
  • The test n > 0 && (1 << 30) % n == 0 relies on 230, the largest power of two in an int, whose only divisors are smaller powers of two.

Taking a logarithm is not safe. Math.log(1 << 29) / Math.log(2) gives 29.000000000000004 instead of 29, so a "whole number?" check rejects a real power of two.

Java Solution

The method isPowerOfTwo is a single return line that works in these steps:

  1. First, check n > 0. If it fails, && stops there and the method returns false.
  2. Compute n - 1, which turns the lowest 1 bit of n into 0 and the zeros to its right into 1s.
  3. AND it with n and return whether the result is 0, which means n had a single 1 bit.

The main method passes each test number to a helper named show. It prints the number, its bits from Integer.toBinaryString, the bit test on its own, and the answer from isPowerOfTwo. The numbers are the three examples, 12, 230, the largest int, 0, -16 and Integer.MIN_VALUE.

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

Output
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.toBinaryString leaves out zeros on the left, so 16 shows as 10000 and 3 as 11, two 1 bits. The line for 1073741824, which is 230, has one 1 followed by 30 zeros and answers true. The line under it, 2147483647, is 31 ones and answers false.

Look at the line for 0: the bit test alone says true, and only the n > 0 check turns the answer into false. The last line, -2147483648, is the same case: a single 1 at position 31 passes the bit test, but the number is negative. The number -16 shows all 32 bits, 28 ones and then 0000, and fails both checks.

The inner parentheses in (n & (n - 1)) == 0 matter. In Java, == is applied before &, so n > 0 && n & (n - 1) == 0 asks for n & ((n - 1) == 0), an int ANDed with a boolean. That version does not compile: Java stops with "bad operand types for binary operator '&'".

Complexity

The method does the same few operations on one int, whatever its value.

  • 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 n - 1 for the moment of the AND.