返回介绍

solution / 1800-1899 / 1812.Determine Color of a Chessboard Square / README_EN

发布于 2024-06-17 01:03:14 字数 4028 浏览 0 评论 0 收藏 0

1812. Determine Color of a Chessboard Square

中文文档

Description

You are given coordinates, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference.

Return true_ if the square is white, and _false_ if the square is black_.

The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first, and the number second.

 

Example 1:

Input: coordinates = "a1"
Output: false
Explanation: From the chessboard above, the square with coordinates "a1" is black, so return false.

Example 2:

Input: coordinates = "h3"
Output: true
Explanation: From the chessboard above, the square with coordinates "h3" is white, so return true.

Example 3:

Input: coordinates = "c7"
Output: false

 

Constraints:

  • coordinates.length == 2
  • 'a' <= coordinates[0] <= 'h'
  • '1' <= coordinates[1] <= '8'

Solutions

Solution 1: Find the Pattern

By observing the chessboard, we find that two squares $(x_1, y_1)$ and $(x_2, y_2)$ with the same color satisfy that both $x_1 + y_1$ and $x_2 + y_2$ are either odd or even.

Therefore, we can get the corresponding coordinates $(x, y)$ from coordinates. If $x + y$ is odd, then the square is white, return true, otherwise return false.

The time complexity is $O(1)$, and the space complexity is $O(1)$.

class Solution:
  def squareIsWhite(self, coordinates: str) -> bool:
    return (ord(coordinates[0]) + ord(coordinates[1])) % 2 == 1
class Solution {
  public boolean squareIsWhite(String coordinates) {
    return (coordinates.charAt(0) + coordinates.charAt(1)) % 2 == 1;
  }
}
class Solution {
public:
  bool squareIsWhite(string coordinates) {
    return (coordinates[0] + coordinates[1]) % 2;
  }
};
func squareIsWhite(coordinates string) bool {
  return (coordinates[0]+coordinates[1])%2 == 1
}
function squareIsWhite(coordinates: string): boolean {
  return ((coordinates.charCodeAt(0) + coordinates.charCodeAt(1)) & 1) === 1;
}
impl Solution {
  pub fn square_is_white(coordinates: String) -> bool {
    let s = coordinates.as_bytes();
    ((s[0] + s[1]) & 1) == 1
  }
}
/**
 * @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;
};
bool squareIsWhite(char* coordinates) {
  return (coordinates[0] + coordinates[1]) & 1;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文