Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions number-of-1-bits/ready-oun.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
class Solution {
public int hammingWeight(int n) {
int count = 0;

while (n != 0) {
if ((n & 1) == 1) {
count++;
}
n = n >>> 1;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍
>>이 아닌 >>>에 대해 찾아 볼 수 있었습니다.
0으로 채우다보니 while 조건도 0이 아니기만 하면 되는 것 같네요!

}

return count;
}
}

/**
Time: O(1) – max 32 iterations (fixed bit size)
Space: O(1)

How it works: Shift each bit → Check → Count → Shift again
1. Shift each bit of n to the right
2. Check if the last bit is 1 using n & 1
3. If it is, increment the count
4. Shift n to the right using n = n >>> 1

Learned:
(n & 1) isolates the least significant bit (LSB) to check if it’s 1
>> : Arithmetic shift (fills in sign bit, so infinite loop for negatives)
>>> : Logical shift (always fills with 0, safe for negatives)
Java evaluates == before &, so use parentheses to control the order
*/
Loading