判断国际象棋棋盘中一个格子的颜色【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); } }