Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 030b383

Browse files
committed
2017/3/31
1 parent 4a6d82d commit 030b383

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

No191_Numberof1Bits.cpp

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
2+
3+
// For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.
4+
5+
6+
class Solution {
7+
public:
8+
// Right shift and count
9+
int hammingWeight(uint32_t n) {
10+
int res = 0;
11+
12+
while(n!=0){
13+
if(n&1){
14+
res++;
15+
}
16+
n = n>>1;
17+
}
18+
return res;
19+
}
20+
};

0 commit comments

Comments
 (0)