Leet Code OJ 292. Nim Game [Difficulty: Easy]

来源:互联网 发布:ps做淘宝宝贝详情教程 编辑:程序博客网 时间:2024/05/01 23:53

题目:
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.

分析:
题意是2个人玩游戏,桌上有一堆石头,一次只能拿1到3个石头,谁把最后的石头拿走,谁就是赢家。现在,你是第一次拿石头的人。写程序来判断,给定石头数n,你是否可以必赢。

简单来说,撇去第一次拿的石头,无论对方拿几个,你都要有应对的数量。对方出1时,2人组合出的数量是2~4;对方出2时,组合出的数量是3~5;对方出3时,数量是4~6。也就是4这个数字是无论对方出什么,都可以组合出来的。故,我们将每4个石头作为一组。假设总数是4的倍数,那无论你每次拿什么,对方都可以跟你组成4,最终的石头一定是对方拿的;反之,如果不是4的倍数,你只要把除以4的余数,在第一次拿走,从第二次开始,无论对方出什么,都组成4,你就必赢了。

代码实现1:

public class Solution {    public boolean canWinNim(int n) {        if(n%4==0){            return false;        }else{            return true;        }    }}

代码实现2:

public class Solution {    public boolean canWinNim(int n) {        int nk=n&3;        return nk != 0;    }}
0 0
原创粉丝点击