/
Solution.java
38 lines (34 loc) · 995 Bytes
/
Solution.java
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
package com.nateshao.sword_offer.topic_12_hammingWeight;
/**
* @date Created by 邵桐杰 on 2021/11/20 12:03
* @微信公众号 千羽的编程时光
* @个人网站 www.nateshao.cn
* @博客 https://nateshao.gitee.io
* @GitHub https://github.com/nateshao
* @Gitee https://gitee.com/nateshao
* Description: 二进制中1的个数
*/
public class Solution {
public static void main(String[] args) {
int hammingWeight = hammingWeight(11);
System.out.println("hammingWeight = " + hammingWeight);
int hammingWeight2 = hammingWeight2(11);
System.out.println("hammingWeight2 = " + hammingWeight2);
}
public static int hammingWeight(int n) {
int res = 0;
while (n != 0) {
res += n & 1;
n >>>= 1;
}
return res;
}
public static int hammingWeight2(int n) {
int res = 0;
while (n != 0) {
res++;
n &= n - 1;
}
return res;
}
}