(一)一个简单的取物游戏的算法

来源:互联网 发布:横截面数据举例 编辑:程序博客网 时间:2024/05/30 22:51

博主是一个java菜鸟,偶然间朋友推荐博主找leetcode.com上的算法从简单到难没事就写几个,所以博主决定每一到两天贴出一个自己写的算法code,因为是新手,代码一定显得拙劣,希望能和大神以及编程爱好者们相互交流,共同提高。以下是今天的算法和code:


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.

(简单讲就是一个两个人玩的取物游戏,每个人能取1到3个数,取到最后一个数的人赢)


public class Nim {public boolean canWinNim(int num) {// num是石头的数量ArrayList array = new ArrayList();for (int i = 0; i < num; i++) {array.add(i);}System.out.println("石头的数量为:" + num + "\n");int m = (num - 1) % 4;// 4个一组以后还剩的数量为mint p = (num - 1) / 4;// 4个一组一共有p组if (m == 3) {System.out.println("后手赢,稳的一逼!!\n");} else {System.out.println("先手赢,稳的一逼!!\n");}if (num > 4) {System.out.println("需要取得数为:");for (int o = 0; o < p; o++) {System.out.print((m + 1 + 4 * o) + " ");}return true;}return false;}}


代码一定有不足,希望大神提出宝贵建议~大笑

1 0
原创粉丝点击