Lintcode Medium title: Coins in a lines coin line

Source: Internet
Author: User
Tags lintcode

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.