Determine Color of a Chessboard Square

Here’s how you can solve the problem:

The board is an 8x8 grid, where each cell alternates in color. We know that all cells with an even sum of their row and column indices are one color (say, white), and the cells with an odd sum are the other color (say, black).

  1. We can use the ASCII values of the characters to determine the row and column indices. In Python, you can use the ord() function to get an ASCII value, and subtract the ASCII value of ‘a’ or ‘1’ to get a zero-based index.
  2. Then, you can add the row and column indices together. If the sum is even, the square is white, and if the sum is odd, the square is black.

Here’s the code:

1
2
3
4
5
class Solution:
    def squareIsWhite(self, coordinates: str) -> bool:
        row = ord(coordinates[0]) - ord('a')
        col = int(coordinates[1]) - 1
        return (row + col) % 2 != 0

In the code, the ord() function is used to convert the characters to their ASCII values. Then, we subtract the ASCII values of ‘a’ and ‘1’ to get the zero-based indices for the row and column. We add these indices together and check whether the sum is even or odd to determine the color of the square.