You are playing the following Nim Game with your friend:
Given n
, the number of stones in the heap, return true
if you can win the game assuming both you and your friend play optimally, otherwise return false
.
n
that we can expect?
n
is a positive integer, and reasonable constraints would be 1 <= n <= 2^31 - 1
.The problem can be solved using a bit of mathematical insight rather than a complex algorithm.
Observation:
From this basis, you can observe the following pattern:
n % 4 == 0
, you will lose because no matter how you play, the number of stones you leave for your friend is a multiple of 4, leading to a losing position.n % 4 != 0
, you will win because you can always adjust your play to leave a multiple of 4 stones for your friend, ensuring their loss.Thus, the solution is simply to check if n
is a multiple of 4.
public class Solution {
public boolean canWinNim(int n) {
return n % 4 != 0;
}
}
n % 4
and compare it to 0 is done in constant time.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?