53
53
54
54
<!-- 这里可写通用的实现逻辑 -->
55
55
56
- ** 方法一:奇偶判断 **
56
+ ** 方法一:找规律 **
57
57
58
- 根据 ` coordinates ` 获取对应的坐标 $(x, y)$,如果 $(x + y)$ 为奇数,则格子为白色,返回 ` true ` ,否则返回 ` false ` 。
58
+ 观察棋盘我们发现,颜色相同的两个格子 $(x_1, y_1)$ 和 $(x_2, y_2)$ 满足 $x_1 + y_1$ 和 $x_2 + y_2$ 均为奇数或偶数。
59
+
60
+ 因此,我们可以根据 ` coordinates ` 获取对应的坐标 $(x, y)$,如果 $x + y$ 为奇数,则格子为白色,返回 ` true ` ,否则返回 ` false ` 。
59
61
60
62
时间复杂度 $O(1)$。
61
63
68
70
``` python
69
71
class Solution :
70
72
def squareIsWhite (self , coordinates : str ) -> bool :
71
- x = ord (coordinates[0 ]) - ord (' a' ) + 1
72
- y = int (coordinates[1 ])
73
- return ((x + y) & 1 ) == 1
73
+ return (ord (coordinates[0 ]) + ord (coordinates[1 ])) % 2 == 1
74
74
```
75
75
76
76
### ** Java**
@@ -80,9 +80,7 @@ class Solution:
80
80
``` java
81
81
class Solution {
82
82
public boolean squareIsWhite (String coordinates ) {
83
- int x = coordinates. charAt(0 ) - ' a' + 1 ;
84
- int y = coordinates. charAt(1 ) - ' 0' ;
85
- return ((x + y) & 1 ) == 1 ;
83
+ return (coordinates. charAt(0 ) + coordinates. charAt(1 )) % 2 == 1 ;
86
84
}
87
85
}
88
86
```
@@ -93,9 +91,7 @@ class Solution {
93
91
class Solution {
94
92
public:
95
93
bool squareIsWhite(string coordinates) {
96
- int x = coordinates[ 0] - 'a' + 1;
97
- int y = coordinates[ 1] - '0';
98
- return ((x + y) & 1) == 1;
94
+ return (coordinates[ 0] + coordinates[ 1] ) % 2;
99
95
}
100
96
};
101
97
```
@@ -104,9 +100,7 @@ public:
104
100
105
101
```go
106
102
func squareIsWhite(coordinates string) bool {
107
- x := coordinates[0] - 'a' + 1
108
- y := coordinates[1] - '0'
109
- return ((x + y) & 1) == 1
103
+ return (coordinates[0]+coordinates[1])%2 == 1
110
104
}
111
105
```
112
106
@@ -118,9 +112,9 @@ func squareIsWhite(coordinates string) bool {
118
112
* @return {boolean}
119
113
*/
120
114
var squareIsWhite = function (coordinates ) {
121
- const x = coordinates .charAt (0 ).charCodeAt () - ' a ' . charCodeAt () + 1 ;
122
- const y = Number ( coordinates .charAt (1 ));
123
- return (( x + y) & 1 ) == 1 ;
115
+ const x = coordinates .charAt (0 ).charCodeAt ();
116
+ const y = coordinates .charAt (1 ). charCodeAt ( );
117
+ return (x + y) % 2 == 1 ;
124
118
};
125
119
```
126
120
0 commit comments