0%

LeetCode-191

题目

191. 位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;
}
}

Go

1
2
3
4
5
6
7
8
9
10
func hammingWeight(num uint32) int {
cnt := 0
for _, v := range strconv.FormatUint(uint64(num),2) {
if v == '1' {
cnt++
}
}
return cnt
}