Problem
Number of 1 Bits
You are given an unsigned integer n. Return the number of 1 bits in its binary representation.
You may assume n is a non-negative integer which fits within 32-bits.
Examples
Example 1:
Input: n = 00000000000000000000000000010111
Output: 4
Example 2:
Input: n = 01111111111111111111111111111101
Output: 30
Constraints
You should aim for a solution with O(1) time and O(1) space.
Solution
Shift bits right, and increment if trailing 1.
class Solution {
public:
int hammingWeight(uint32_t n) {
int count = 0;
while (n) {
count += (n % 2) ? 1 : 0;
n = n >> 1;
}
return count;
}
};