判断国际象棋棋盘中一个格子的颜色【LC1812】
You are given
coordinates, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference.
写不完的本子…
-
思路:找规律,当坐标的横坐标和纵坐标的奇偶性一致时,颜色为黑色;反之为白色
-
实现
class Solution { public boolean squareIsWhite(String coordinates) { int x = coordinates.charAt(0) - 'a'; int y = coordinates.charAt(1) - '1'; if (x % 2 == y % 2){ return false; } return true; } }-
复杂度
- 时间复杂度:O(1)O(1)O(1)
- 空间复杂度:O(1)O(1)O(1)
-
-
实现:位运算
class Solution { public boolean squareIsWhite(String coordinates) { return ( coordinates.charAt(0) - 'a' & 1 ) != (coordinates.charAt(1) - '1' & 1); } }

本文介绍了一种快速判断国际象棋棋盘上任意格子颜色的方法。通过分析坐标特性,利用位运算技巧,实现了高效的颜色判断逻辑。文章提供了一个简洁的Java实现示例。

被折叠的 条评论
为什么被折叠?



