July 31, 2016

# LeetCode - 292 - Nim Game

### Problem

You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones. Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap. For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.

Try it out: http://leetcode.com/problems/nim-game/

Java - 0ms

``````public class Solution {
/*
public boolean canWinNim(int n) {
//Original Code
//Case 1 : n = 1/2/3 , always last one
if (n < 4){
return true;
//Case 2 : n = 4 , always lose
}else if (n == 4){
return false;
//Case 3 : n = 5/6/7 , always win,
//because you can take 1/2/3 stones to make your opponents stone set into 4.
}else if (n % 4 > 0){
return true;
}
//Case 4 : n = 4 multiple , always lose.
return false;
}
*/
//Shorten version
public boolean canWinNim(int n){
if (n % 4 > 0 || n < 4 ) return true;
return false;
}

}
``````

Javascript - 100ms

``````/**
* @param {number} n
* @return {boolean}
*/
var canWinNim = function(n) {
return  (n%4 > 0 || n < 4);
};
``````