Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Power of Two Check Implementation in Java

11 min readbeginner
Website QA and SEO audits

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

A power-of-two test asks whether a positive integer has exactly one bit set: 1, 2, 4, 8, 16, and so on. The standard trick is n > 0 combined with n & (n - 1) == 0, because subtracting one flips the lowest set bit and every bit below it, so the AND clears to zero only when there was a single set bit to begin with. Engineers reach for it when sizing hash tables, ring buffers and allocator blocks, where a power-of-two capacity turns an expensive modulo into a cheap mask (i & (cap - 1)), and when validating an alignment argument before handing it to a lower layer.

Power of Two Check in Java: what you actually reach for

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.

Java implementation

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. They also want >>> rather than >> anywhere the value under test is shifted, since >> sign-extends and turns a negative into a run of ones. Provide separate int and long overloads instead of widening at the call site, and never accept Integer where int will do.
java
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 Free

The Java-specific 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. 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.

Performance in Java, beyond the O(1)

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. The asymptotic cost is the same in every language, O(1) time and O(1) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Power of Two Check between languages.

Real-World Applications

Power of Two Check applies wherever its problem shape appears in your own code. In Java, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Power of Two Check helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Power of Two Check appears frequently in phone screens and early-round coding interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Power of Two Check over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Power of Two Check to build pattern recognition. In Java, demonstrate proficiency with generics and streams API to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Java code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Before paying for Replit, check its student and free-tier options on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.