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