Skip to content

Commit 41032c9

Browse files
committed
feat: add python and java solutions to lcof problem
添加《剑指 Offer》题解:面试题15. 二进制中1的个数
1 parent 53d5f83 commit 41032c9

File tree

3 files changed

+80
-0
lines changed

3 files changed

+80
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# [题目](这里是题目链接,如:https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/)
2+
3+
## 题目描述
4+
请实现一个函数,输入一个整数,输出该数二进制表示中 1 的个数。例如,把 9 表示成二进制是 1001,有 2 位是 1。因此,如果输入 9,则该函数输出 2。
5+
6+
**示例 1:**
7+
8+
```
9+
输入:00000000000000000000000000001011
10+
输出:3
11+
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。
12+
```
13+
14+
**示例 2:**
15+
16+
```
17+
输入:00000000000000000000000010000000
18+
输出:1
19+
解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 '1'。
20+
```
21+
22+
**示例 3:**
23+
24+
```
25+
输入:11111111111111111111111111111101
26+
输出:31
27+
解释:输入的二进制串 11111111111111111111111111111101 中,共有 31 位为 '1'。
28+
```
29+
30+
## 解法
31+
`n & (n - 1)` 会消除 n 中最后一位中的 1。
32+
33+
### Python3
34+
```python
35+
class Solution:
36+
def hammingWeight(self, n: int) -> int:
37+
res = 0
38+
while n:
39+
n &= (n - 1)
40+
res += 1
41+
return res
42+
```
43+
44+
### Java
45+
```java
46+
public class Solution {
47+
// you need to treat n as an unsigned value
48+
public int hammingWeight(int n) {
49+
int res = 0;
50+
while (n != 0) {
51+
n &= (n - 1);
52+
++res;
53+
}
54+
return res;
55+
}
56+
}
57+
```
58+
59+
### ...
60+
```
61+
62+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
public class Solution {
2+
// you need to treat n as an unsigned value
3+
public int hammingWeight(int n) {
4+
int res = 0;
5+
while (n != 0) {
6+
n &= (n - 1);
7+
++res;
8+
}
9+
return res;
10+
}
11+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
class Solution:
2+
def hammingWeight(self, n: int) -> int:
3+
res = 0
4+
while n:
5+
n &= (n - 1)
6+
res += 1
7+
return res

0 commit comments

Comments
 (0)