Math Fundamentals18 sections · 814 units
Open in Course

Problem - Number of 1 Bits

LeetCode 191

Given an unsigned integer nn, return the number of 1 bits in its binary representation (also called Hamming weight).

For example, if n=11n = 11 (which is 101121011_2), the answer is 3 because there are three 1s. If n=128n = 128 (which is 10000000210000000_2), the answer is 1.

This is your first bit manipulation problem. Think about how you can check each bit of nn and count the 1s. Before reading on, try to sketch an algorithm yourself.