Skip to content

Commit df0a013

Browse files
committed
Add Solution.java for 0461.Hamming Distance
1 parent 5b703c5 commit df0a013

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Hamming Distance
2+
3+
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
4+
5+
Given two integers _x_ and _y_, calculate the Hamming distance.
6+
7+
## Example 1:
8+
```
9+
Input: x = 1, y = 4
10+
Output: 2
11+
12+
Explanation:
13+
1 (0 0 0 1)
14+
4 (0 1 0 0)
15+
↑ ↑
16+
The above arrows point to positions where the corresponding bits are different.
17+
```
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
class Solution {
2+
public int hammingDistance(int x, int y) {
3+
int count = 0, sum = x ^ y;
4+
while (sum != 0) {
5+
sum &= (sum - 1);
6+
count++;
7+
}
8+
return count;
9+
}
10+
}

0 commit comments

Comments
 (0)