Number of 1 Bits

EasyBit Manipulationbit count

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given a non-negative integer n, return the number of 1 bits present in its binary representation. This quantity is sometimes called the *Hamming weight* or *population count* of the number. For example, the integer 11 is written in binary as 1011, which contains three set bits, so the answer is 3. You should treat n purely as the integer value it represents and count how many of its bits are equal to 1. **Follow-up:** Can you solve it without examining every single bit position, ideally in time proportional to the number of set bits rather than the total bit width?

Examples

Input: n = 11
Output: 3
11 in binary is `1011`, which has three bits set to 1.
Input: n = 128
Output: 1
128 in binary is `10000000`, which has a single bit set to 1.
Input: n = 0
Output: 0
0 in binary is `0`, which has no bits set to 1.

Constraints

  • `0 <= n <= 2^31 - 1`
  • `n` is a non-negative integer.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.