Skip to content

Commit 0a438f5

Browse files
committed
solve 461.hamming-distance
1 parent 170ec98 commit 0a438f5

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

vscode/461.hamming-distance.java

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/*
2+
* @lc app=leetcode id=461 lang=java
3+
*
4+
* [461] Hamming Distance
5+
*
6+
* https://leetcode.com/problems/hamming-distance/description/
7+
*
8+
* algorithms
9+
* Easy (70.04%)
10+
* Total Accepted: 230.2K
11+
* Total Submissions: 327.9K
12+
* Testcase Example: '1\n4'
13+
*
14+
* The Hamming distance between two integers is the number of positions at
15+
* which the corresponding bits are different.
16+
*
17+
* Given two integers x and y, calculate the Hamming distance.
18+
*
19+
* Note:
20+
* 0 ≤ x, y < 2^31.
21+
*
22+
*
23+
* Example:
24+
*
25+
* Input: x = 1, y = 4
26+
*
27+
* Output: 2
28+
*
29+
* Explanation:
30+
* 1 (0 0 0 1)
31+
* 4 (0 1 0 0)
32+
* ⁠ ↑ ↑
33+
*
34+
* The above arrows point to positions where the corresponding bits are
35+
* different.
36+
*
37+
*
38+
*/
39+
class Solution {
40+
public int hammingDistance(int x, int y) {
41+
int result = x ^ y;
42+
int count = 0;
43+
while (result != 0) {
44+
result = result & (result - 1);
45+
count++;
46+
}
47+
return count;
48+
}
49+
}
50+

0 commit comments

Comments
 (0)