博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Nim Game
阅读量:4099 次
发布时间:2019-05-25

本文共 1464 字,大约阅读时间需要 4 分钟。

题目链接:

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.

这个题目也比较简单,关键还是考察我们对数字观察的能力,题目已经告诉我们有4个石子的时候是啥情况了,意思就是你无论咋拿,收尾的肯定是对方,那么你就输了。

如果没石子的时候,应该返回false;

如果有1个石子,我全拿走,他玩儿完,返回true;
如果有2个石子,我全拿走,他玩儿完,返回true;
如果有3个石子,我全拿走,他玩儿完,返回true;
如果有4个石子,无论我怎么拿,都是人家收盘,返回false;
如果有5个石子,我拿走1个,对方无论怎么拿,他都得完蛋,返回true;
如果有6个石子,我拿走2个,对方无论怎么拿,他都得完蛋,返回true;
如果有7个石子,我拿走3个,对方无论怎么拿,他都得完蛋,返回true;
如果有8个石子,我无论怎么拿,他给我留4个(注意这一场景),我完蛋,返回false;
如果有9个石子,……

好了,写到这里差不多了,详细已经看出点门道了,如果谁最后接盘的是4个石子,那就完蛋。

下面是Java的代码实现:

public class NimGame {
public boolean canWinNim(int n) { if (n == 0) return false; if (n <= 3) return true; if (n == 4) return false; return !(n % 4 == 0); } public static void main(String[] args) { NimGame nimGame = new NimGame(); for (int i = 0; i < 100; i++) { System.out.println(i + ": "+ nimGame.canWinNim(i)); } }}

转载地址:http://xkhii.baihongyu.com/

你可能感兴趣的文章
Linux的SOCKET编程 简单演示
查看>>
正则匹配函数
查看>>
Linux并发服务器编程之多线程并发服务器
查看>>
聊聊gcc参数中的-I, -L和-l
查看>>
[C++基础]034_C++模板编程里的主版本模板类、全特化、偏特化(C++ Type Traits)
查看>>
C语言内存检测
查看>>
Linux epoll模型
查看>>
Linux select TCP并发服务器与客户端编程
查看>>
Linux系统编程——线程池
查看>>
基于Visual C++2013拆解世界五百强面试题--题5-自己实现strstr
查看>>
Linux 线程信号量同步
查看>>
C++静态成员函数访问非静态成员的几种方法
查看>>
类中的静态成员函数访问非静态成员变量
查看>>
C++学习之普通函数指针与成员函数指针
查看>>
C++的静态成员函数指针
查看>>
Linux系统编程——线程池
查看>>
yfan.qiu linux硬链接与软链接
查看>>
Linux C++线程池实例
查看>>
shared_ptr简介以及常见问题
查看>>
c++11 你需要知道这些就够了
查看>>