Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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!

https://leetcode.com/problems/number-of-1-bits/
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.