class Solution:
def canWinNim(self, n: int) -> bool:
return n % 4 != 0
class Solution {
public:
bool canWinNim(int n) {
return n % 4 != 0;
}
};
class Solution {
public boolean canWinNim(int n) {
return n % 4 != 0;
}
}
var canWinNim = function(n) {
return n % 4 !== 0;
};
The Nim Game is a classic two-player game where there is a heap of n
stones on a table. Players take turns removing 1, 2, or 3 stones from the heap. The player who removes the last stone wins the game.
You are given the number of stones n
. You always go first. Each player takes turns optimally. The task is to determine whether you can win the game, assuming both players play optimally.
Constraints:
n
≤ 231 - 1
The first instinct might be to simulate all possible moves, trying every possible number of stones to remove at each turn. However, this quickly becomes impractical for large values of n
. Instead, we look for a pattern or mathematical insight.
By considering small values of n
, we notice that:
Let's break down the solution step-by-step:
n
is not a multiple of 4, you can always win by removing enough stones to leave a multiple of 4 for your opponent. For example, if n % 4 == 1
, take 1 stone; if n % 4 == 2
, take 2 stones; and so on.
True
if n % 4 != 0
, otherwise return False
.
n
instantly.
Let's walk through an example with n = 7
:
Brute-force approach:
n % 4
and compare it to 0.The Nim Game problem demonstrates how a simple mathematical insight can replace brute-force simulation. By recognizing that multiples of 4 are losing positions, we can solve the problem in constant time and space. The elegance of this solution lies in its simplicity and the power of pattern recognition in combinatorial games.