number_of_1_bits
1# @leet start 2class Solution: 3 def hammingWeight(self, n: int) -> int: 4 """ 5 The count of one bits in a number can be done by bitwise ANDing the 6 number `n` with itself minus 1 `n - 1`. 7 The reason why this works is that if a bit is set in `n`, in `n - 1`, 8 its least significant bit will become 0. 9 Thus, if we AND the numbers together, the least significant bit is removed. 10 We count how many times we do this until the number hits 0 to remove 11 all of the one bits. 12 """ 13 count = 0 14 while n: 15 count += 1 16 n &= n - 1 17 return count 18 19 20# @leet end 21sol = Solution() 22 23 24def test(): 25 assert sol.hammingWeight(11) == 3 26 assert sol.hammingWeight(128) == 1
class
Solution:
3class Solution: 4 def hammingWeight(self, n: int) -> int: 5 """ 6 The count of one bits in a number can be done by bitwise ANDing the 7 number `n` with itself minus 1 `n - 1`. 8 The reason why this works is that if a bit is set in `n`, in `n - 1`, 9 its least significant bit will become 0. 10 Thus, if we AND the numbers together, the least significant bit is removed. 11 We count how many times we do this until the number hits 0 to remove 12 all of the one bits. 13 """ 14 count = 0 15 while n: 16 count += 1 17 n &= n - 1 18 return count
def
hammingWeight(self, n: int) -> int:
4 def hammingWeight(self, n: int) -> int: 5 """ 6 The count of one bits in a number can be done by bitwise ANDing the 7 number `n` with itself minus 1 `n - 1`. 8 The reason why this works is that if a bit is set in `n`, in `n - 1`, 9 its least significant bit will become 0. 10 Thus, if we AND the numbers together, the least significant bit is removed. 11 We count how many times we do this until the number hits 0 to remove 12 all of the one bits. 13 """ 14 count = 0 15 while n: 16 count += 1 17 n &= n - 1 18 return count
The count of one bits in a number can be done by bitwise ANDing the
number n with itself minus 1 n - 1.
The reason why this works is that if a bit is set in n, in n - 1,
its least significant bit will become 0.
Thus, if we AND the numbers together, the least significant bit is removed.
We count how many times we do this until the number hits 0 to remove
all of the one bits.
sol =
<Solution object>
def
test():