191. Number of 1 Bits

  • 38.8%

https://leetcode.com/problems/number-of-1-bits/?tab=Description

Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight).

1
2
For example, the 32-bit integer ’11' has binary representation
00000000000000000000000000001011, so the function should return 3.

方法一:

我的代码实现:

Oct 14, 2017

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
int hammingWeight(uint32_t n) {
int cnt = 0;
while(n){
n &= n-1;
cnt++;
}
return cnt;
}
};

https://discuss.leetcode.com/topic/9915/short-code-of-c-o-m-by-time-m-is-the-count-of-1-s-and-another-several-method-of-o-1-time

1
2
3
4
5
6
7
8
9
10
int hammingWeight(uint32_t n)
{
int res = 0;
while(n)
{
n &= n - 1;
++ res;
}
return res;
}

my code

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
int hammingWeight(uint32_t n) {
int res = 0;
while(n){
res += 1;
n = n&(n-1);
}
return res;
}
};

java


https://discuss.leetcode.com/topic/11385/simple-java-solution-bit-shifting

1
2
3
4
5
6
7
8
public static int hammingWeight(int n) {
int ones = 0;
while(n!=0) {
ones = ones + (n & 1);
n = n>>>1;
}
return ones;
}
谢谢你,可爱的朋友。