292. Nim Game (pick-and-play) by Python

Source: Internet
Author: User

292. Nim Game topic:

You were playing the following Nim Game with your friend:there was a heap of stones on the table and each time one of your take Turns to remove 1 to 3 stones. The one who removes, the last stone would be the winner. You'll take the first turn to remove the stones.

Both of you is very clever and has optimal strategies for the game. Write a function to determine whether your can win the game given the number of stones in the heap.

For example, if there is 4 stones in the heap and then you'll never win the Game:no matter 1, 2, or 3 stones you remove, The last stone is always being removed by your friend.

There is a pile of stones on the table, only one at a time, you take the number of stones and ask if you can win.

Answer:
Class solution (Object):
def canwinnim (self, N):
"""
: Type N:int
: Rtype:bool
"""
If n% 4:
Return True
Else
Return False

A brain twist, figured out will become very simple, that is, if the stone is a multiple of four who first Take x, the other can take 4-x, so that the last remaining 4 when the first take will lose,
So as long as you first take, let the number of stones into a multiple of 4, you can let each other lose, so as long as the number of verification is not a multiple of 4 can be.

292. Nim Game (pick-and-play) by Python

Related Article

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.