LeetCode 1908: Game of Nim Solution
Master LeetCode problem 1908 (Game of Nim), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1908. Game of Nim
Problem Explanation
Explanation
The Game of Nim is a two-player game where players take turns removing stones from distinct piles. On each turn, a player must remove at least one stone, and they can remove any number of stones from a single pile. The player who removes the last stone wins the game.
To determine the winning strategy for the Nim game, we need to understand the concept of Nim sum. The Nim sum of a set of piles is calculated by XOR-ing the number of stones in each pile. If the Nim sum is 0, then the current player will lose the game, otherwise, they can win by making a move that leads to a Nim sum of 0.
For the Game of Nim with n piles, the winning strategy is to make the Nim sum of the initial state non-zero. This strategy guarantees that the player who starts the game can always win by making the correct moves.
Solution Code
public boolean nimGame(int[] piles) {
int nimSum = 0;
for (int stones : piles) {
nimSum ^= stones;
}
return nimSum != 0;
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1908 (Game of Nim)?
This page provides optimized solutions for LeetCode problem 1908 (Game of Nim) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1908 (Game of Nim)?
The time complexity for LeetCode 1908 (Game of Nim) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1908 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1908 in Java, C++, or Python.