Number of 1 Bits
Part of Practice: Counting & Canceling
You are given an integer n that should be read as a 32-bit binary value. Return how many of its bits are 1. This count is called the Hamming weight (the number of set bits — bits that equal 1 — in a binary number).
For example, 11 in binary is 1011, which contains three 1 bits. The follow-up asks: if this function is called many times, can you make it faster than checking all 32 bit positions every call?
Examples
- Input:
- n = 11
- Output:
- 3
11 in binary is 1011, which has three 1 bits.
- Input:
- n = 128
- Output:
- 1
128 in binary is 10000000 — a single 1 bit followed by zeros.
- Input:
- n = 2147483645
- Output:
- 30
Its 31-bit binary form is all 1s except the bit worth 2, giving 30 ones.
Hints
One at a time — struggle first, peek second.
Your thinking space — verify on LeetCode, then mark it.