:orphan: Number of 1 Bits ================ .. highlight:: none Problem ------- https://leetcode.com/problems/number-of-1-bits/ Write a function that takes the binary representation of a positive integer and returns the number of **set bits** it has (also known as the `Hamming weight `_). **Example 1:** :: Input: n = 11 Output: 3 Explanation: The input binary string 1011 has a total of three set bits. **Example 2:** :: Input: n = 128 Output: 1 Explanation: The input binary string 10000000 has a total of one set bit. **Example 3:** :: Input: n = 2147483645 Output: 30 Explanation: The input binary string 1111111111111111111111111111101 has a total of thirty set bits. **Constraints:** - ``1 <= n <= 2``\ :sup:`31`\ ``- 1`` .. highlight:: python Pattern ------- Bit Manipulation Approaches ---------- .. tab-set:: .. tab-item:: Bit Scan **Code** .. literalinclude:: ../problems/medium/number-of-1-bits/number_of_1_bits__bit_scan.py :language: python :lines: 12- **Test** >>> from number_of_1_bits__bit_scan import hammingWeight >>> hammingWeight(11) 3 >>> hammingWeight(128) 1 >>> hammingWeight(2147483645) 30 .. autofunction:: number_of_1_bits__bit_scan.hammingWeight .. tab-item:: Brian Kernighan **Code** .. literalinclude:: ../problems/medium/number-of-1-bits/number_of_1_bits__brian_kernighan.py :language: python :lines: 12- **Test** >>> from number_of_1_bits__brian_kernighan import hammingWeight >>> hammingWeight(11) 3 >>> hammingWeight(128) 1 >>> hammingWeight(2147483645) 30 .. autofunction:: number_of_1_bits__brian_kernighan.hammingWeight