Easy
Number of 1 Bits
Easy
0 submissions
10 coins
+50 XP
Bit Manipulation
Divide and Conquer
Problem Description
## Problem
Given a positive integer `n`, write a function that returns the number of **set bits** (bits equal to `1`) in its binary representation. This is also known as the **Hamming weight**.
## Examples
**Example 1:**
```
Input: n = 11
Output: 3
Explanation: 11 in binary is 1011, which has three 1-bits.
```
**Example 2:**
```
Input: n = 128
Output: 1
Explanation: 128 in binary is 10000000, which has one 1-bit.
```
**Example 3:**
```
Input: n = 255
Output: 8
Explanation: 255 in binary is 11111111, which has eight 1-bits.
```
## Hints
- Use `n & 1` to check the least significant bit, then right-shift `n`.
- Alternatively, use the bit trick `n = n & (n - 1)` which clears the lowest set bit each iteration — count how many times you apply it before `n` becomes 0.
- In Python, `bin(n).count('1')` works but try the bit manipulation approach.
Constraints
- The input is treated as an unsigned 32-bit integer.
- `0 <= n <= 2^32 - 1`
Need help?
Connect with expert programmers for real-time collaborative coding, video meetings, and whiteboard sessions via CodeConnect.
Video Call
Whiteboard
Live Coding
Screen Share