Count how many bits are set to 1 in the binary representation of a non-negative integer.
Number of 1 Bits
Given a non-negative integer n, return the number of set bits in its binary representation.
A set bit is a bit with value 1.
For example, the binary representation of 11 is 1011, which contains 3 set bits.
Goal
Write a function that computes the total count of 1 bits in n.
Notes
- You may assume
nis a non-negative integer. - The answer is the number of positions whose bit value is
1.
Input Format
- A single non-negative integer
n.
Output Format
- Return an integer representing the number of set bits in
n.
Constraints
- The exact upper bound is platform-dependent and may be treated as a standard integer size.
Example 1
Input
n = 11
Output
3
Explanation
11 in binary is 1011, which has three 1 bits.
Example 2
Input
n = 128
Output
1
Explanation
128 in binary is 10000000, which has one 1 bit.
Show 1 more example
Example 3
Input
n = 0
Output
0
Explanation
0 in binary has no set bits.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.