Nim Game

原创 2015年11月21日 11:31:39

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.

Hint:

If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner?

思路: 容易知道当石头的数目是4的倍数时,先手肯定会输,只要后手使得自己拿下的石头后,剩下的石头的数目是4的倍数,后手就会赢。

当石头的数目不是4的倍数时,先手先拿石头后,剩下的数目是4的倍数肯定后手会输。

public class Solution {
    public boolean canWinNim(int n) {

        return n % 4 ==0 ? false : true;      

    }
}

相关文章推荐

HDU 3389 Game(nim博弈)

Game Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) ...

Nim Game

You are playing the following Nim Game with your friend: There is a heap of stones on the table, eac...

Leetcode:292. Nim Game

Leetcode题解292.Nim Game-Easy题目

UVA 11859 Division Game (Nim博弈)

题目:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=32746 题意:有一个n*m(1 分析:考虑每个数包含的素因子个数(...
  • w20810
  • w20810
  • 2015年08月26日 21:17
  • 509

Division Game UVA - 11859 (Nim)题解

Division Game UVA - 11859 (Nim)题解

Leetcode - Nim Game

You are playing the following Nim Game with your friend: There is a heap of stones on the table, eac...

leetCode 292. Nim Game

题目连接:https://leetcode.com/problems/nim-game/     题目内容: You are playing the following Nim Game ...

LeetCode 292: Nim Game 题解

别看题这么长,其实很简单。LeetCode 292: Nim Game Problem: You are playing the following Nim Game with your fr...
  • Artprog
  • Artprog
  • 2016年08月16日 23:18
  • 348

山东省第二届 ACM 省赛 Simple Game (Nim+Bash)

Problem Description Here is a simple game. In this game, there are several piles of stones and two...

LeetCode Algorithms 292. Nim Game 题解

题目: You are playing the following Nim Game with your friend: There is a heap of stones on the tab...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Nim Game
举报原因:
原因补充:

(最多只允许输入30个字)