October 5, 2024
We're solving another LeetCode problem today instead of adding a new project to my portfolio. This one is focused on bit manipulation. Let's dive in.
Today's problem is 191. Number of 1 bits. The problem is as follows: Write a function that takes the binary representation of a positive integer and returns the number of set bits it has (also known as the Hamming weight).
Let's answer using the UMPIRE method:
1def countBits(self, n: int) -> int:2 b = bin(n)3 s = str(b)[2:]4 count = 05 for bit in s:6 if bit == '1':7 count += 18 return count
1def test_reverseBits(self):2 assert self.countBits(4) == 13 assert self.reverseBits(3) == 2
Second LeetCode Blog Post
Another LeetCode Blog Post