TRT
Sign in
easyFoundationsLeetCode#bit manipulation

Number of 1 bits

Count how many bits are set in the binary form of a 32-bit unsigned integer.

The Runtime Theory Team1 min read
Taught inBits, bytes and number representationEvery value a program stores is a row of bits. How integers are laid out in bytes, how negative numbers work, and why adding 1 can turn a huge number negative.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inn = 11

out3

inn = 128

out1

inn = 2147483645

out30

Given a positive integer that fits in 32 bits, return the number of 1 bits in its binary representation (its population count, or Hamming weight).

Before you code

11 is 1011 in binary, so the answer is 3. The direct approach checks the lowest bit, shifts right and repeats: 32 steps at most. A neater trick clears one set bit per step, so it loops only as many times as there are 1s.

Hints

  1. n & 1 is the lowest bit. n >> 1 shifts every bit one place right.
  2. n & (n - 1) clears the lowest set bit. Subtracting 1 flips the lowest 1 and every 0 below it, so the AND removes exactly that 1.
  3. Most languages also have a built-in, such as Integer.bitCount in Java or int.bit_count() in Python 3.10+. Write the loop first, then compare.

Production & complexity notes

When solving Number of 1 bits on LeetCode (easy), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Bits, bytes and number representation to reinforce the underlying pattern.

What it practices

Reading an integer as the row of bits it really is, from Bits, bytes and number representation.

Not started

Sign in to save your learning progress.

Sign in to save