Leetcode 1812. Determine Color of a Chessboard Square
You are given a coordinate coordinates
that represents the position of a square on a standard 8x8 chessboard. Chessboard squares are identified by a letter and a number, where the letter represents the column (‘a’ to ‘h’) and the number represents the row (1 to 8).
Return true
if the square is white, and false
if the square is black.
For example:
coordinates
be outside the scope of the chessboard dimensions (a-h) and (1-8)?
coordinates
will always be valid and within the chessboard dimensions.To determine the color of the chessboard square:
a
to h
translates to 1 to 8).#include <iostream>
using namespace std;
bool squareIsWhite(string coordinates) {
// Convert col letter to number: 'a' -> 1, 'b' -> 2, ..., 'h' -> 8
int col = coordinates[0] - 'a' + 1;
// Row number as integer
int row = coordinates[1] - '0';
// Determine color based on parity of sum of col and row
return (col + row) % 2 != 0;
}
int main() {
// Example test cases
cout << squareIsWhite("a1") << endl; // Output: 0 (False)
cout << squareIsWhite("h3") << endl; // Output: 0 (False)
cout << squareIsWhite("c7") << endl; // Output: 1 (True)
return 0;
}
The time complexity of this solution is (O(1)) since converting the column letter, converting the row number, and computing the sum parity are all constant-time operations. The space complexity is also (O(1)).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?