Topic
coins lined up in line
A n
coin is lined up in a line. Two contestants took the 1 or 2 coins in turn from the right until there were no coins. The man who gets the last coin wins.
Please decide whether the first player loses or wins?
Sample Example
n = 1
, returns true
.
n = 2
, returns true
.
n = 3
, returns false
.
n = 4
, returns true
.
n = 5
, returns true
.
challenges
O (1) time complexity and O (1) storage.
Solving
Two people in one take, when the first person to take is 1 o'clock, the second person to take is 2; when the first person takes the 2 o'clock, the second person takes 1. This takes a value of 3. This is a sequence of 3 cycles, when only three coins left, not silly also know how to take. Just consider the case of only three coins.
n = 1
, returns true
.
n = 2
, returns true
.
n = 3
, returns false
.
Attention:
The sequence of the format of the coin can be: (2,1), (a), (a), rather than strictly according to the (()) sequence to take coins
Solving
According to the example given above, it is very simple to write down the following procedure
Public class Solution { /** @param n:an integer @return : A Boolean which equals to True if the first player would win */ Public boolean firstwillwin (int n) { // Write your code here return n%3!=0;} }
Of course, it can be recursive.
Public classSolution {/** * @paramN:an Integer *@return: A Boolean which equals to True if the first player would win*/ Public BooleanFirstwillwin (intN) {//Write your code here if(n==1| | n==2) return true; if(N==0 | | N==3) return false; returnFirstwillwin (n-3); }}
Lintcode Medium title: Coins in a lines coin line