Number of 1 Bits
Examples
Example 1:
Input: n = 00000000000000000000000000010111
Output: 4
Example 2:
Input: n = 01111111111111111111111111111101
Output: 30
Example 1:
Input: n = 00000000000000000000000000010111
Output: 4
Example 2:
Input: n = 01111111111111111111111111111101
Output: 30
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.
Use the bit trick n &= n - 1 to clear the lowest set bit each time. Count how many times this can be done before n becomes zero.
Each operation removes exactly one 1 bit from the binary representation of n. Therefore, the number of iterations equals the number of set bits.
O(k) where k is the number of set bitsO(1)class Solution:
def hammingWeight(self, n: int) -> int:
count = 0
while n:
n &= n - 1
count += 1
return count