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'
This problem asks to determine whether a given chessboard square is white or black based on its coordinates.
Understanding the Pattern:
A chessboard has an alternating pattern of black and white squares. Notice that:
Algorithm:
Extract Coordinates: The input coordinates
string contains the column letter (a-h) and the row number (1-8).
Convert to Numbers: Convert the column letter to its corresponding numerical value (a=1, b=2, ..., h=8). The row number is already numerical.
Calculate the Sum: Add the numerical representations of the column and row.
Check Parity: Check if the sum is even or odd. If odd, the square is white; if even, it's black.
Time and Space Complexity:
Code Implementation (Python):
class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
col = ord(coordinates[0]) - ord('a') + 1 # Convert column letter to number
row = int(coordinates[1]) # Row number is already an integer
return (col + row) % 2 != 0 # Check if sum is odd (white)
Code Implementation (Java):
class Solution {
public boolean squareIsWhite(String coordinates) {
int col = coordinates.charAt(0) - 'a' + 1;
int row = coordinates.charAt(1) - '0';
return (col + row) % 2 != 0;
}
}
Code Implementation (C++):
class Solution {
public:
bool squareIsWhite(string coordinates) {
int col = coordinates[0] - 'a' + 1;
int row = coordinates[1] - '0';
return (col + row) % 2 != 0;
}
};
Other Languages (Similar Approach): The core logic remains consistent across different programming languages. The only variation lies in the syntax and data type handling. For instance, character-to-integer conversion might slightly vary. The provided solution section in the original prompt demonstrates this adaptability across several other languages.
Optimization Note: The % 2
operation is efficient, directly checking for oddness. There's no significant performance optimization to be gained here.