File tree 4 files changed +81
-6
lines changed
solution/0400-0499/0461.Hamming Distance
4 files changed +81
-6
lines changed Original file line number Diff line number Diff line change 33
33
34
34
<!-- 这里可写通用的实现逻辑 -->
35
35
36
+ 利用异或运算的规律找出不同的位
37
+
38
+ - 0 ^ 0 = 0
39
+ - 1 ^ 1 = 0
40
+ - 0 ^ 1 = 1
41
+ - 1 ^ 0 = 1
42
+
36
43
<!-- tabs:start -->
37
44
38
45
### ** Python3**
39
46
40
47
<!-- 这里可写当前语言的特殊实现逻辑 -->
41
48
42
49
``` python
43
-
50
+ class Solution :
51
+ def hammingDistance (self , x : int , y : int ) -> int :
52
+ num, count = x ^ y, 0
53
+ while num != 0 :
54
+ num &= num - 1
55
+ count += 1
56
+ return count
44
57
```
45
58
46
59
### ** Java**
47
60
48
61
<!-- 这里可写当前语言的特殊实现逻辑 -->
49
62
50
63
``` java
64
+ class Solution {
65
+ public int hammingDistance (int x , int y ) {
66
+ int num = x ^ y;
67
+ int count = 0 ;
68
+ while (num != 0 ) {
69
+ num &= num - 1 ;
70
+ count++ ;
71
+ }
72
+ return count;
73
+ }
74
+ }
75
+ ```
76
+
77
+ 或者利用库函数 ` Integer.bitCount() `
51
78
79
+ ``` java
80
+ class Solution {
81
+ public int hammingDistance (int x , int y ) {
82
+ return Integer . bitCount(x ^ y);
83
+ }
84
+ }
52
85
```
53
86
54
87
### ** ...**
Original file line number Diff line number Diff line change @@ -38,18 +38,51 @@ The above arrows point to positions where the corresponding bits are different.
38
38
39
39
## Solutions
40
40
41
+ Use xor operation to find different bits.
42
+
43
+ - 0 ^ 0 = 0
44
+ - 1 ^ 1 = 0
45
+ - 0 ^ 1 = 1
46
+ - 1 ^ 0 = 1
47
+
41
48
<!-- tabs:start -->
42
49
43
50
### ** Python3**
44
51
45
52
``` python
46
-
53
+ class Solution :
54
+ def hammingDistance (self , x : int , y : int ) -> int :
55
+ num, count = x ^ y, 0
56
+ while num != 0 :
57
+ num &= num - 1
58
+ count += 1
59
+ return count
47
60
```
48
61
49
62
### ** Java**
50
63
51
64
``` java
65
+ class Solution {
66
+ public int hammingDistance (int x , int y ) {
67
+ int num = x ^ y;
68
+ int count = 0 ;
69
+ while (num != 0 ) {
70
+ num &= num - 1 ;
71
+ count++ ;
72
+ }
73
+ return count;
74
+ }
75
+ }
76
+ ```
77
+
78
+ Or use the library function ` Integer.bitCount() `
52
79
80
+ ``` java
81
+ class Solution {
82
+ public int hammingDistance (int x , int y ) {
83
+ return Integer . bitCount(x ^ y);
84
+ }
85
+ }
53
86
```
54
87
55
88
### ** ...**
Original file line number Diff line number Diff line change 1
1
class Solution {
2
2
public int hammingDistance (int x , int y ) {
3
- int count = 0 , sum = x ^ y ;
4
- while (sum != 0 ) {
5
- sum &= (sum - 1 );
3
+ // return Integer.bitCount(x ^ y);
4
+ int num = x ^ y ;
5
+ int count = 0 ;
6
+ while (num != 0 ) {
7
+ num &= num - 1 ;
6
8
count ++;
7
9
}
8
10
return count ;
9
11
}
10
- }
12
+ }
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def hammingDistance (self , x : int , y : int ) -> int :
3
+ num , count = x ^ y , 0
4
+ while num != 0 :
5
+ num &= num - 1
6
+ count += 1
7
+ return count
You can’t perform that action at this time.
0 commit comments