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,2,3的时候,肯定可以赢,为4的时候不可能赢,为5的时候,相当于对方1,2,3的情况。为6的时候,第一次取2相当于对方4的时候,所以可以赢。以此类推,只要数量不是4的倍数,就可以赢
import java.util.Scanner;
import javax.swing.text.StyledEditorKit.BoldAction;
public class Solution {
public static void main(String[] args) {
// TODO Auto-generated method stub
int n;
boolean b=true;
Scanner in= new Scanner(System.in);
n=in.nextInt();
Solution solution=new Solution();
b=solution.canWinNim(n);
if(b)
{
System.out.println("可以赢");
}else
{
System.out.println("不能赢");
}
}
public boolean canWinNim(int n) {
boolean b=true;
if(n%4==0)
{
b=false;
}else
{
b=true;
}
return b;
}
}