File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
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
+ */
You can’t perform that action at this time.
0 commit comments