Power of Two Check Implementation in Java
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Power of Two Check runs in O(1) time and O(1) space, in Java as in every other language.
- ✓java.lang.Integer and java.lang.Long carry the primitives: Integer.bitCount(int), Integer.highestOneBit, Integer.lowestOneBit, Integer.numberOfLeadingZeros and Integer.numberOfTrailingZeros, each with a Long counterpart.
- ✓The parentheses in (n & (n - 1)) == 0 are mandatory in Java, because & has lower precedence than ==, and a reviewer flags their absence as a compile error waiting to happen on a boolean operand.
- ✓The Java trap: Java has no unsigned int, so the sign bit is an ordinary value bit and Integer.MIN_VALUE has exactly one bit set: Integer.bitCount(Integer.MIN_VALUE) is 1, and (n & (n - 1)) == 0 holds for it too.
- ✓Integer.bitCount is an intrinsic candidate, so C2 replaces it with POPCNT once the method is hot, but the first few thousand invocations run interpreted or through tier-1 C1 code, which is why a microbenchmark without warmup measures the JIT rather than the instruction.
What Power of Two Check actually is
Power of Two Check in Java: what you actually reach for
Java implementation
import java.math.BigInteger;
public final class PowerOfTwo {
private PowerOfTwo() {}
// '&' has LOWER precedence than '==' in Java: the parentheses are mandatory.
public static boolean isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
public static boolean isPowerOfTwo(long n) {
return n > 0L && Long.bitCount(n) == 1;
}
public static void main(String[] args) {
System.out.println(isPowerOfTwo(1024)); // true
System.out.println(isPowerOfTwo(Integer.MIN_VALUE)); // false
// Why the n > 0 guard is not optional:
System.out.println(Integer.bitCount(Integer.MIN_VALUE)); // 1
System.out.println(Math.abs(Integer.MIN_VALUE)); // -2147483648
System.out.println(Integer.highestOneBit(1000)); // 512
System.out.println(Integer.numberOfTrailingZeros(1024)); // 10
System.out.println(BigInteger.ONE.shiftLeft(200).bitCount()); // 1
}
}
Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Java-specific trap
Performance in Java, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for Power of Two Check?
java.lang.Integer and java.lang.Long carry the primitives: Integer.bitCount(int), Integer.highestOneBit, Integer.lowestOneBit, Integer.numberOfLeadingZeros and Integer.numberOfTrailingZeros, each with a Long counterpart. The JDK ships no isPowerOfTwo; com.google.common.math.IntMath.isPowerOfTwo in Guava is the ecosystem answer when that dependency is already present. For values wider than 64 bits, java.math.BigInteger provides bitCount(), bitLength() and testBit(int), and BigInteger.ONE.shiftLeft(k) constructs the value to test.
What is the most common Java mistake when implementing Power of Two Check?
Java has no unsigned int, so the sign bit is an ordinary value bit and Integer.MIN_VALUE has exactly one bit set: Integer.bitCount(Integer.MIN_VALUE) is 1, and (n & (n - 1)) == 0 holds for it too. The defence people reach for makes things worse, because Math.abs(Integer.MIN_VALUE) is documented to return Integer.MIN_VALUE, still negative, so 'normalise then test' converts the trap into a confident false positive. Only an explicit n > 0 rescues it. C# throws OverflowException on the equivalent Math.Abs call; Java returns quietly.
How does Power of Two Check actually perform in Java?
Integer.bitCount is an intrinsic candidate, so C2 replaces it with POPCNT once the method is hot, but the first few thousand invocations run interpreted or through tier-1 C1 code, which is why a microbenchmark without warmup measures the JIT rather than the instruction. Autoboxing is where the real cost hides: a List<Integer> or Stream<Integer> of candidate sizes allocates an Integer per element outside the -128..127 valueOf cache, so boxing dominates the bit test by orders of magnitude. Use int[] and IntStream. Time complexity is O(1) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Replit, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.