Number of 1 Bits
Easy · Bit Manipulation
You are given a non-negative integer. Count how many bits in its binary representation are set to 1. Return that count as an integer.
Examples
Input: n = 11
Output: 3
Why: 11 in binary is 1011, which has three 1 bits.
Input: n = 128
Output: 1
Why: 128 in binary is 10000000, which has a single 1 bit.
Input: n = 0
Output: 0
Why: 0 has no set bits.
Constraints
0 <= n <= 2^31 - 1
Practise it by voice
Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.
This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Number of 1 Bits. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.