Ben Chuanlong Du's Blog

It is never too late to learn.

Count Ones in the Binary Represeantion of Integers

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

In [ ]:
https://leetcode.com/problems/number-of-1-bits/
In [ ]:
class Solution:
    def hammingWeight(self, n: int) -> int:
        num_ones = 0
        while n > 0:
            num_ones += 1
            n &= n - 1
        return num_ones

Notice that there's a built-in method int.bit_count to do this in Python 3.10+. Unsigned integer types in Rust also has a method named count_ones to do this.

In [ ]:
 
In [ ]:
 

Comments