Skip to content

Files

Latest commit

9324b58 · Jun 15, 2023

History

History

1812.Determine Color of a Chessboard Square

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
Mar 16, 2022
Jun 15, 2023
Jun 15, 2023
Feb 6, 2023
Dec 8, 2022
Dec 8, 2022
Feb 6, 2023
Dec 8, 2022
Dec 8, 2022
Dec 8, 2022
Dec 8, 2022

English Version

题目描述

给你一个坐标 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 均为奇数或偶数。

因此,我们可以根据 coordinates 获取对应的坐标 ( x , y ) ,如果 x + y 为奇数,则格子为白色,返回 true,否则返回 false

时间复杂度 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
}

JavaScript

/**
 * @param {string} coordinates
 * @return {boolean}
 */
var squareIsWhite = function (coordinates) {
    const x = coordinates.charAt(0).charCodeAt();
    const y = coordinates.charAt(1).charCodeAt();
    return (x + y) % 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
    }
}

C

bool squareIsWhite(char* coordinates) {
    return (coordinates[0] + coordinates[1]) & 1;
}

...