Skip to content

Commit 8038a0b

Browse files
Merge pull request #177 from satyam878/satyam1
Count 1's bit
2 parents 5eb61be + e7b67b0 commit 8038a0b

1 file changed

Lines changed: 19 additions & 0 deletions

File tree

LeetCode/count1s.java

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

0 commit comments

Comments
 (0)