number-of-1-bits.py
bit-manipulation/number-of-1-bits.py · Python · 1021 B · 2026-02-02 21:16
# Count the number of times n & 1 # bit # O(1) time (there's at most 32 bits), O(1) space # Shifting the number def hammingWeight(n: int) -> int: num_ones = 0 while n > 0: num_ones += 1 if n & 1 else 0 n = n >> 1 return num_ones # Removing the right-most 1 bit at each loop pass # - Subtracting 1 from a number flips the rightmost 1 bit to 0 and turns all bits to its right into 1 # - Performing n & (n - 1) removes the rightmost 1 bit from n def hammingWeight(n: int) -> int: res = 0 while n: n &= n - 1 res += 1 return res # Shifting the 1 def hammingWeight(n: int) -> int: res = 0 for i in range(32): if (1 << i) & n: res += 1 return res def hammingWeight(n: int) -> int: return bin(n).count('1') # The Hamming weight of a string is the number of symbols that are different from the zero-symbol of the alphabet used. # It is thus equivalent to the Hamming distance from the all-zero string of the same length