00:00

Problem Statement

Input/Output Examples

Visual Explanation

Subtracting 1 flips the lowest 1 bit to 0 and all the 0 bits below it to 1. AND-ing with the original then clears exactly that one bit.

Approaches

Both approaches handle negative numbers. Kernighan's loop runs once per 1 bit; the shift loop always checks 32 bits.

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

Kernighan's loop runs once per set bit, at most 32 times; the shift loop always runs 32 times. Both are constant time for an int.

Interview Tips and Recommended Approach

  • Use >>>, not >>. With >>, a negative number never reaches 0.
  • Explain why n & (n - 1) works with a small binary example.
  • Know Integer.bitCount(). The JDK uses a branch-free parallel counting trick.
  • Reuse the trick. n & (n - 1) == 0 also tests for a power of two.

Recommended Approach: Kernighan's Algorithm

Why: it runs only as many times as there are 1 bits and teaches the most useful bit trick in interviews.