LeetCode 3274: Check if Two Chessboard Squares Have the Same Color (Math / Simulation)
English
On a chessboard, square color is determined by coordinate parity. Convert each square like "a1" into (col + row) % 2. Two squares have the same color if those parity values are equal.
class Solution {
public boolean checkTwoChessboards(String c1, String c2) {
int p1 = (c1.charAt(0) - 'a' + c1.charAt(1) - '1') % 2;
int p2 = (c2.charAt(0) - 'a' + c2.charAt(1) - '1') % 2;
return p1 == p2;
}
}func checkTwoChessboards(c1 string, c2 string) bool {
p1 := (int(c1[0]-'a') + int(c1[1]-'1')) % 2
p2 := (int(c2[0]-'a') + int(c2[1]-'1')) % 2
return p1 == p2
}class Solution {
public:
bool checkTwoChessboards(string c1, string c2) {
int p1 = (c1[0]-'a' + c1[1]-'1') % 2;
int p2 = (c2[0]-'a' + c2[1]-'1') % 2;
return p1 == p2;
}
};class Solution:
def checkTwoChessboards(self, c1: str, c2: str) -> bool:
p1 = (ord(c1[0]) - ord('a') + ord(c1[1]) - ord('1')) % 2
p2 = (ord(c2[0]) - ord('a') + ord(c2[1]) - ord('1')) % 2
return p1 == p2var checkTwoChessboards = function(c1, c2) {
const p1 = ((c1.charCodeAt(0) - 97) + (c1.charCodeAt(1) - 49)) % 2;
const p2 = ((c2.charCodeAt(0) - 97) + (c2.charCodeAt(1) - 49)) % 2;
return p1 === p2;
};中文
国际象棋棋盘格子的颜色由坐标奇偶性决定。把 "a1" 这类坐标转成 (列偏移 + 行偏移) % 2,两个格子的结果相同就同色,不同就异色。
class Solution {
public boolean checkTwoChessboards(String c1, String c2) {
int p1 = (c1.charAt(0) - 'a' + c1.charAt(1) - '1') % 2;
int p2 = (c2.charAt(0) - 'a' + c2.charAt(1) - '1') % 2;
return p1 == p2;
}
}func checkTwoChessboards(c1 string, c2 string) bool {
p1 := (int(c1[0]-'a') + int(c1[1]-'1')) % 2
p2 := (int(c2[0]-'a') + int(c2[1]-'1')) % 2
return p1 == p2
}class Solution {
public:
bool checkTwoChessboards(string c1, string c2) {
int p1 = (c1[0]-'a' + c1[1]-'1') % 2;
int p2 = (c2[0]-'a' + c2[1]-'1') % 2;
return p1 == p2;
}
};class Solution:
def checkTwoChessboards(self, c1: str, c2: str) -> bool:
p1 = (ord(c1[0]) - ord('a') + ord(c1[1]) - ord('1')) % 2
p2 = (ord(c2[0]) - ord('a') + ord(c2[1]) - ord('1')) % 2
return p1 == p2var checkTwoChessboards = function(c1, c2) {
const p1 = ((c1.charCodeAt(0) - 97) + (c1.charCodeAt(1) - 49)) % 2;
const p2 = ((c2.charCodeAt(0) - 97) + (c2.charCodeAt(1) - 49)) % 2;
return p1 === p2;
};