Quick revision
The short answer
A positive int is a power of two exactly when n > 0 && (n & (n - 1)) == 0, because n - 1 flips the lowest set bit and every bit below it, so the AND clears that bit and leaves zero only if it was the only one. Set bits are counted with Integer.bitCount(n), which the JIT turns into a single popcount instruction on most CPUs, or manually with n &= n - 1 in a loop. The single number among pairs is the XOR of all elements, because x ^ x = 0 and XOR is order independent, in O(n) time and O(1) space.
What to remember
In this answer, we saw that n > 0 && (n & (n - 1)) == 0 detects a power of two because subtracting one clears the lowest set bit. Set bits are counted with Integer.bitCount, a popcount intrinsic, or with the n &= n - 1 loop that runs once per set bit. XOR of all elements finds the single number in O(n) time and O(1) space because pairs cancel. Finally, >>> shifts in zeros while >> keeps the sign, and shift counts are masked to 5 bits for int, so 1 << 32 is 1.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A positive int is a power of two exactly when n > 0 && (n & (n - 1)) == 0, because n - 1 flips the lowest set bit and every bit below it, so the AND clears that bit and leaves zero only if it was the only one. Set bits are counted with Integer.bitCount(n), which the JIT turns into a single popcount instruction on most CPUs, or manually with n &= n - 1 in a loop. The single number among pairs is the XOR of all elements, because x ^ x = 0 and XOR is order independent, in O(n) time and O(1) space.
Why this question is asked
Bit tricks look like puzzles, but they appear in real Java code: hash table sizing, flags packed into an int, permission masks, and the JDK's own collections. Interviewers ask these three together because each one tests a different property of binary arithmetic, and because explaining why they work shows we understand two's complement, the way Java stores negative numbers. In this answer, we will recap the operators, then explain each trick with code and the reason it works, and finish with the two shift pitfalls that catch people: the difference between >> and >>>, and shift counts that wrap.
1A Quick Recap of the Bitwise Operators
Java's int is 32 bits in two's complement, which means the top bit is the sign and -1 is all ones. The operators work on each bit position independently: & is 1 where both bits are 1, | is 1 where either is 1, ^ (XOR) is 1 where the bits differ, and ~ flips every bit. The shifts move bits left or right: << shifts left and fills with zeros, >> shifts right and copies the sign bit into the top, and >>> shifts right and fills the top with zeros. Integer.toBinaryString is handy to see what is happening.
2Checking for a Power of Two
A power of two has exactly one bit set: 8 is 1000, 64 is 1000000. Look at what subtracting 1 does to any number: it turns the lowest set bit into 0 and every 0 below it into 1. So n & (n - 1) is n with its lowest set bit cleared. If n had only one bit set, the result is 0. If it had more, at least one bit remains.
| n | binary n | binary n - 1 | n & (n - 1) |
|---|---|---|---|
| 8 | 1000 | 0111 | 0000 -> power of two |
| 12 | 1100 | 1011 | 1000 -> not |
| 6 | 0110 | 0101 | 0100 -> not |
| 1 | 0001 | 0000 | 0000 -> power of two |
The n > 0 check matters for two cases. For 0, the expression 0 & -1 is 0, so without the guard 0 would look like a power of two. For Integer.MIN_VALUE, which is a single 1 in the sign bit, MIN_VALUE - 1 wraps to MAX_VALUE, the AND is 0, and it would also pass. An equivalent library form is Integer.bitCount(n) == 1 for positive n.
3Counting the Set Bits
The same trick gives a neat counting loop, often called Kernighan's method: each n &= n - 1 removes exactly one set bit, so the number of iterations equals the number of set bits, not the 32 bit positions. For negative numbers we must not loop while n > 0; we loop while n != 0, which works because the trick does not care about the sign.
In real code we use Integer.bitCount or Long.bitCount. They are JIT intrinsics: on CPUs that support a population count instruction, such as POPCNT on x86-64 or the equivalent on ARM, HotSpot replaces the call with that single instruction, which is faster than any loop. The loop is still worth knowing for the interview, because it shows why n & (n - 1) is useful.
4Finding the Single Number With XOR
XOR has three properties that make this work. x ^ x = 0, because every bit equals itself. x ^ 0 = x. And XOR is commutative and associative, so the order of operations does not matter. If we XOR all elements of an array where every number appears twice except one, we can mentally regroup the pairs next to each other, each pair cancels to 0, and what remains is the single number XOR 0, which is the single number.
This is O(n) time and O(1) space, compared with a HashSet solution that needs O(n) extra memory. It works for negative numbers too, since XOR is defined bit by bit. But notice the assumption: it relies on every other number appearing exactly twice. If some appear three times, XOR no longer cancels them, and a different technique, counting each bit position modulo 3, is needed.
5Shift Pitfalls: >> Versus >>> and Masked Shift Counts
The two right shifts differ only for negative numbers. >> is an arithmetic shift: it copies the sign bit, so -16 >> 2 is -4, like division by 4 rounding down. >>> is a logical shift: it fills with zeros, so the result is a large positive number. When we treat an int as a set of bits rather than as a number, for example when looping over the bits of a hash, we want >>>, otherwise a negative value never reaches zero and the loop never ends.
The second pitfall is that Java masks the shift count. For int, only the lowest 5 bits of the count are used, so a shift by 32 is a shift by 0, and for long only the lowest 6 bits are used. This surprises people who expect 1 << 32 to be 0.
So when building masks for bit positions 32 to 63, we must write 1L << i, not 1 << i. Forgetting the L is a classic source of bugs in bitmask code.
6Follow-up questions
How would you find the lowest set bit itself?
n & -n isolates it, because in two's complement -n is ~n + 1, which flips every bit above the lowest set bit. Integer.lowestOneBit(n) does the same, and Integer.numberOfTrailingZeros(n) gives its position.
How do you round up to the next power of two?
For n greater than 1, 1 << (32 - Integer.numberOfLeadingZeros(n - 1)) gives the smallest power of two greater than or equal to n. HashMap uses a similar calculation to size its table, and it must cap the result for values above 2^30 to avoid overflow.
What if the array has two single numbers?
XOR everything to get a ^ b, which is non-zero. Pick any set bit of it, for example with x & -x, and split the array into numbers that have that bit and those that do not. Each group contains one of the singles plus pairs, so XOR within each group gives a and b.
7Conclusion
In this answer, we saw that n > 0 && (n & (n - 1)) == 0 detects a power of two because subtracting one clears the lowest set bit. Set bits are counted with Integer.bitCount, a popcount intrinsic, or with the n &= n - 1 loop that runs once per set bit. XOR of all elements finds the single number in O(n) time and O(1) space because pairs cancel. Finally, >>> shifts in zeros while >> keeps the sign, and shift counts are masked to 5 bits for int, so 1 << 32 is 1.
Open with
For a power of two, I return n greater than zero and n AND n minus one equals zero. A power of two has exactly one bit set, and subtracting one turns that bit off and all the lower bits on, so the AND is zero; with any extra bit set, something survives.
Then, if they want more
The n greater than zero check is there because zero and Integer.MIN_VALUE would otherwise pass. For counting bits, in production I use Integer.bitCount, which HotSpot compiles to a single popcount instruction on modern CPUs.
If asked for a manual version, I loop while n is not zero, doing n AND equals n minus one and counting, which takes one iteration per set bit and also works for negative numbers. For the single number, I XOR all elements together.
XOR of a number with itself is zero, XOR with zero is the number, and the order does not matter, so all pairs cancel and the single value remains, in O(n) time and constant space. I would also mention two pitfalls.
The signed right shift copies the sign bit, so for treating an int as raw bits I use the unsigned shift, triple greater than, which fills with zeros.
And shift counts are masked to five bits for int, so one shifted left by 32 is one, not zero; for masks above bit 31 I need a long, written as 1L shifted left.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write Java methods to check if an int is a power of two, count set bits, and find the...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/fd1c7ac9fe/