1812. 判断国际象棋棋盘中一个格子的颜色
题目描述
给你一个坐标 coordinates
,它是一个字符串,表示国际象棋棋盘中一个格子的坐标。下图是国际象棋棋盘示意图。
如果所给格子的颜色是白色,请你返回 true
,如果是黑色,请返回 false
。
给定坐标一定代表国际象棋棋盘上一个存在的格子。坐标第一个字符是字母,第二个字符是数字。
示例 1:
输入:coordinates = "a1" 输出:false 解释:如上图棋盘所示,"a1" 坐标的格子是黑色的,所以返回 false 。
示例 2:
输入:coordinates = "h3" 输出:true 解释:如上图棋盘所示,"h3" 坐标的格子是白色的,所以返回 true 。
示例 3:
输入:coordinates = "c7" 输出:false
提示:
coordinates.length == 2
'a' <= coordinates[0] <= 'h'
'1' <= coordinates[1] <= '8'
解法
方法一:找规律
观察棋盘我们发现,颜色相同的两个格子 $(x_1, y_1)$ 和 $(x_2, y_2)$ 满足 $x_1 + y_1$ 和 $x_2 + y_2$ 均为奇数或偶数。
因此,我们可以根据 $\textit{coordinates}$ 获取对应的坐标 $(x, y)$,如果 $x + y$ 为奇数,则格子为白色,返回 $\textit{true}$,否则返回 $\textit{false}$。
时间复杂度 $O(1)$,空间复杂度 $O(1)$。
Python3
class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
return (ord(coordinates[0]) + ord(coordinates[1])) % 2 == 1
Java
class Solution {
public boolean squareIsWhite(String coordinates) {
return (coordinates.charAt(0) + coordinates.charAt(1)) % 2 == 1;
}
}
C++
class Solution {
public:
bool squareIsWhite(string coordinates) {
return (coordinates[0] + coordinates[1]) % 2;
}
};
Go
func squareIsWhite(coordinates string) bool {
return (coordinates[0]+coordinates[1])%2 == 1
}
TypeScript
function squareIsWhite(coordinates: string): boolean {
return ((coordinates.charCodeAt(0) + coordinates.charCodeAt(1)) & 1) === 1;
}
Rust
impl Solution {
pub fn square_is_white(coordinates: String) -> bool {
let s = coordinates.as_bytes();
((s[0] + s[1]) & 1) == 1
}
}
JavaScript
/**
* @param {string} coordinates
* @return {boolean}
*/
var squareIsWhite = function (coordinates) {
return (coordinates[0].charCodeAt() + coordinates[1].charCodeAt()) % 2 == 1;
};
C
bool squareIsWhite(char* coordinates) {
return (coordinates[0] + coordinates[1]) & 1;
}