Skip to content

Commit 316e8d3

Browse files
committed
Count1's
1 parent 33ab1ce commit 316e8d3

1 file changed

Lines changed: 18 additions & 0 deletions

File tree

LeetCode/count1s.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
public class Solution {
2+
// you need to treat n as an unsigned value
3+
public int hammingWeight(int n) {
4+
5+
int cnt=0;
6+
int len=0;
7+
while(len<32)
8+
{
9+
if((n&1)==1) //perform bitwise AND and count 1's
10+
{
11+
cnt++;
12+
}
13+
n=n>>1; //right shift digit by one bit
14+
len++;
15+
}
16+
return cnt;
17+
}
18+
}

0 commit comments

Comments
 (0)