Write a function to check whether an integer is a power of two.

A positive power of two has exactly one bit set in binary (1, 10, 100, 1000 ...). Subtracting 1 flips that bit and sets all lower bits, so n & (n - 1) is 0 only for powers of two.

Key Points

public class PowerOfTwo {

    static boolean isPowerOfTwo(int n) {
        return n > 0 && (n & (n - 1)) == 0;
    }

    public static void main(String[] args) {
        int[] tests = {1, 16, 18, 0, -8, 1073741824};
        for (int n : tests) {
            System.out.println(n + " -> " + isPowerOfTwo(n) + " (bitCount: " + (n > 0 && Integer.bitCount(n) == 1) + ")");
        }
    }
}

Output

1 -> true (bitCount: true)

16 -> true (bitCount: true)

18 -> false (bitCount: false)

0 -> false (bitCount: false)

-8 -> false (bitCount: false)

1073741824 -> true (bitCount: true)

Good to Know

For 16 the check is 10000 & 01111 = 0, while for 18 it is 10010 & 10001 = 10000, which is not 0.

Explain the bit pattern with one small example; interviewers want to see that you understand why n & (n - 1) works, not just the formula.

Common Mistakes

Follow-up Questions

Interview Tip

A concise interview answer is

A positive power of two has exactly one set bit, so I return n > 0 && (n & (n - 1)) == 0, because subtracting 1 clears that single bit. It runs in O(1), and Integer.bitCount(n) == 1 is an equally good, more readable alternative.

Last updated: 11 November 2026

Previous question: Add the digits of a number repeatedly until a single digit remains.

Next question: Move all zeros to the end of an array while keeping the order of the other elements.

More Java Coding Questions interview questions

All Java Coding Questions questions