給你一個坐標(biāo) coordinates ,它是一個字符串,表示國際象棋棋盤中一個格子的坐標(biāo)。下圖是國際象棋棋盤示意圖。如果所給格子的顏色是白色,請你返回 true,如果是黑色,請返回 false 。給定坐標(biāo)一定代表國際象棋棋盤上一個存在的格子。坐標(biāo)第一個字符是字母,第二個字符是數(shù)字。

exp
例子:
輸入: coordinates = "a1"
輸出: false
解釋: 如上圖棋盤所示,"a1" 坐標(biāo)的格子是黑色的,所以返回 false 。
輸入:coordinates = "h3"
輸出:true
解釋:如上圖棋盤所示,"h3" 坐標(biāo)的格子是白色的,所以返回 true 。
解題思路:
方法1
全排列, 這種相對較快一些, 也比較容易理解
func squareIsWhite(_ coordinates: String) -> Bool {
let arr = ["a1", "c1", "e1", "g1", "b2", "d2", "f2", "h2",
"a3", "c3", "e3", "g3", "b4", "d4", "f4", "h4",
"a5", "c5", "e5", "g5", "b6", "d6", "f6", "h6",
"a7", "c7", "e7", "g7", "b8", "d8", "f8", "h8"];
return !arr.contains(coordinates)
}
方法2
奇偶特點, 轉(zhuǎn)成ascii碼, 我們會發(fā)現(xiàn)x, y之和偶數(shù)為黑, 奇數(shù)為白, 根據(jù)這個特點可以處理
這里可以多種方法處理, 余數(shù), &操作等都可
func squareIsWhite(_ coordinates: String) -> Bool {
// 轉(zhuǎn)成ascii碼進行余數(shù)判斷, 一行代碼可以, 只不過比較長
let a = coordinates.first!.asciiValue, b = coordinates.last!.asciiValue
return (a! + b!) % 2 == 1
}
題目來源:力扣(LeetCode) 感謝力扣爸爸 :)
IOS 算法合集地址