Determine Color of a Chessboard Square in Java

Ah, the classic chessboard dilemma! You know, the one that keeps you up at night, pondering the existential question: “Is this square white or black?” Well, fear not, my friend! We’re here to solve this pressing issue with a sprinkle of sarcasm and a dash of coding magic.

Imagine you’re at a fancy chess tournament, and you’re trying to impress your friends with your knowledge of chessboard squares. You confidently point to a square and declare, “This one is white!” only to be met with a chorus of laughter. Oops! Turns out, you need a little help from Java to determine the color of that pesky square.

Problem Description

The problem is simple: Given the coordinates of a square on a chessboard (like “a1” or “h8”), you need to determine if that square is white or black. The chessboard is an 8×8 grid, and the colors alternate. So, if you’re on a white square, the next square in any direction is black, and vice versa.

Solution in Java


class Solution {
  public boolean squareIsWhite(String coordinates) {
    final char letter = coordinates.charAt(0);
    final char digit = coordinates.charAt(1);
    return letter % 2 != digit % 2;
  }
}

Approach

The approach here is as straightforward as it gets. The code takes the first character (the letter) and the second character (the digit) from the input string. It then checks if the sum of their ASCII values is even or odd. If they are of different parity (one is even, the other is odd), the square is white; otherwise, it’s black. Simple, right?

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(1)
Space Complexity O(1)

Real-World Example

Let’s say you’re at a chess club, and you’re trying to figure out if your next move will land you on a white square. You glance at the board and see the coordinates “d4”. Using our Java solution, you can quickly determine that “d4” is indeed a white square. Now you can confidently make your move without the fear of being laughed at!

Similar Problems

If you enjoyed this problem, you might want to check out these related challenges: