-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberOf1Bits.java
More file actions
66 lines (62 loc) · 1.92 KB
/
NumberOf1Bits.java
File metadata and controls
66 lines (62 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。
//
//
//
// 示例 1:
//
// 输入:00000000000000000000000000001011
//输出:3
//解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。
//
//
// 示例 2:
//
// 输入:00000000000000000000000010000000
//输出:1
//解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 '1'。
//
//
// 示例 3:
//
// 输入:11111111111111111111111111111101
//输出:31
//解释:输入的二进制串 11111111111111111111111111111101 中,共有 31 位为 '1'。
//
//
//
// 提示:
//
//
// 请注意,在某些语言(如 Java)中,没有无符号整数类型。在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响您的实现,因为无论整数是有符号的
//还是无符号的,其内部的二进制表示形式都是相同的。
// 在 Java 中,编译器使用二进制补码记法来表示有符号整数。因此,在上面的 示例 3 中,输入表示有符号整数 -3。
//
//
//
//
// 进阶:
//如果多次调用这个函数,你将如何优化你的算法?
// Related Topics 位运算
// 👍 222 👎 0
package leetcode.editor.cn;
/**
* [191]位1的个数
*/
public class NumberOf1Bits {
//leetcode submit region begin(Prohibit modification and deletion)
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
while(n != 0) {
count++;
n &= (n - 1);
}
return count;
}
}
//leetcode submit region end(Prohibit modification and deletion)
public static void main(String[] args) {
Solution solution = new NumberOf1Bits().new Solution();
}
}