Skip to content

Commit c63cce6

Browse files
committed
Solve problem '191) number of 1 bits'
1 parent e10d3a5 commit c63cce6

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the [Hamming weight](https://en.wikipedia.org/wiki/Hamming_weight)).
2+
3+
**Note:**
4+
5+
- Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
6+
- In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 3**, the input represents the signed integer. `-3`.
7+
8+
**Example 1:**
9+
10+
```
11+
Input: n = 00000000000000000000000000001011
12+
Output: 3
13+
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
14+
```
15+
16+
**Example 2:**
17+
18+
```
19+
Input: n = 00000000000000000000000010000000
20+
Output: 1
21+
Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.
22+
```
23+
24+
**Example 3:**
25+
26+
```
27+
Input: n = 11111111111111111111111111111101
28+
Output: 31
29+
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.
30+
```
31+
32+
**Constraints:**
33+
34+
- The input must be a **binary string** of length `32`.
35+
36+
**Follow up:** If this function is called many times, how would you optimize it?
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package main
2+
3+
import "fmt"
4+
5+
func main() {
6+
fmt.Println(hammingWeight(11))
7+
fmt.Println(hammingWeight(128))
8+
fmt.Println(hammingWeight(4294967293))
9+
}
10+
11+
func hammingWeight(num uint32) int {
12+
count := 0
13+
for num > 0 {
14+
if num%2 == 1 {
15+
count++
16+
}
17+
num /= 2
18+
}
19+
return count
20+
}

0 commit comments

Comments
 (0)