Number of 1 Bits

Easy~10 min

Given a positive integer n, write a function that returns the number of set bits (1-bits) in its binary representation. This is also known as the Hamming weight.

Examples

Example 1
Input: n = 11
Output: 3
Explanation: The binary representation of 11 is 1011, which has three set bits.
Example 2
Input: n = 128
Output: 1
Explanation: The binary representation of 128 is 10000000, which has one set bit.
Example 3
Input: n = 2147483645
Output: 30
Explanation: The binary representation of 2147483645 is 1111111111111111111111111111101, which has 30 set bits.

Constraints

  • 1 <= n <= 2^31 - 1
  • Expected time complexity: O(log n)
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run