00:00

Problem Statement

Input/Output Examples

Visual Explanation

The n > 0 check is required: 0 also gives 0 for the AND, and Integer.MIN_VALUE has one 1 bit but is negative.

Approaches

The bit trick answers in constant time. The division loop is the straightforward alternative.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

The bit trick is constant time. The division loop runs at most 31 times for an int, so it is also bounded, but it does more work.

Interview Tips and Recommended Approach

  • Check n > 0 first. It handles 0, negatives and Integer.MIN_VALUE.
  • Know Integer.bitCount(n) == 1 as a readable alternative for positive n.
  • Extend the idea. Powers of four are powers of two whose bit sits in an even position.
  • Know where it is used: hash table sizes, buffer sizes and alignment checks.

Recommended Approach: Bit Trick

Why: it answers in constant time with one expression, and it is the classic demonstration of n & (n - 1).