Skip to content

Commit 5e98d7f

Browse files
authored
Merge pull request neetcode-gh#170 from r1cky0/patch-16
Create 191-Number-of-1-Bits.java
2 parents d698d9b + 3316c2c commit 5e98d7f

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

java/191-Number-of-1-Bits.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
//standard way
2+
public class Solution {
3+
// you need to treat n as an unsigned value
4+
public int hammingWeight(int n) {
5+
int count = 0;
6+
int mask = 1;
7+
for (int i = 0; i < 32; i++) {
8+
if ((n & mask) != 0) {
9+
count++;
10+
}
11+
n >>= 1;
12+
}
13+
return count;
14+
}
15+
}
16+
17+
//smart way
18+
public class Solution {
19+
// you need to treat n as an unsigned value
20+
public int hammingWeight(int n) {
21+
int count = 0;
22+
while (n != 0) {
23+
n = n & (n - 1);
24+
count++;
25+
}
26+
return count;
27+
}
28+
}

0 commit comments

Comments
 (0)