Count the Lit Switches

EasyBit ManipulationFree

Problem

A control panel stores the state of 31 switches as one non-negative integer panel: bit i is 1 when switch i is on.

Return how many switches are on, that is, the number of 1 bits in panel.

Example 1

Input:
panel = 11
Output:
3

11 is 1011 in binary: three bits are set.

Example 2

Input:
panel = 128
Output:
1

Example 3

Input:
panel = 0
Output:
0

Constraints

  • 0 ≤ panel < 2^31

Hint

Show the first hint

You could test each of the 31 bit positions. Can you skip the zero bits entirely?

Walkthrough

How to approach it

01Clarify before coding

  • Is the input always non-negative? Yes, below 2^31, so there is no sign bit to worry about.
  • Do we count switches beyond bit 30? No, there are only 31 switches.

02Brute force

Convert to a binary string and count the '1' characters, or test (panel >> i) & 1 for all 31 positions.

Cost: O(31) per call, which is already fast; the interviewer wants to see whether you know a loop that only touches the set bits.

The rest of the walkthrough is in the app

The full walkthrough (key insight, step-by-step, dry run, complexity, edge cases, pitfalls, follow-ups) and solutions in Python and JavaScript are in the app, next to an editor and a terminal that runs your code against the tests.