0%

剑指offer-15

剑指offer-15 二进制中1的个数

题目

结果

代码

版本一

1
2
3
4
5
6
class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
return Integer.toBinaryString(n).replace("0", "").length();
}
}

版本二

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
String s = Integer.toBinaryString(n);
int count = 0;
for (char ch : s.toCharArray()) {
if (ch == '1') {
count++;
}
}
return count;
}
}