Skip to content

Commit 9914638

Browse files
committed
solve: number of 1 bits
1 parent c5626d3 commit 9914638

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

number-of-1-bits/ready-oun.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution {
2+
public int hammingWeight(int n) {
3+
int count = 0;
4+
5+
while (n != 0) {
6+
if ((n & 1) == 1) {
7+
count++;
8+
}
9+
n = n >>> 1;
10+
}
11+
12+
return count;
13+
}
14+
}
15+
16+
/**
17+
Time: O(1) – max 32 iterations (fixed bit size)
18+
Space: O(1)
19+
20+
How it works: Shift each bit → Check → Count → Shift again
21+
1. Shift each bit of n to the right
22+
2. Check if the last bit is 1 using n & 1
23+
3. If it is, increment the count
24+
4. Shift n to the right using n = n >>> 1
25+
26+
Learned:
27+
(n & 1) isolates the least significant bit (LSB) to check if it’s 1
28+
>> : Arithmetic shift (fills in sign bit, so infinite loop for negatives)
29+
>>> : Logical shift (always fills with 0, safe for negatives)
30+
Java evaluates == before &, so use parentheses to control the order
31+
*/

0 commit comments

Comments
 (0)