Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number N
on the chalkboard. On each player's turn, that player makes a move consisting of:
- Choosing any
x
with0 < x < N
andN % x == 0
. - Replacing the number
N
on the chalkboard withN - x
.
Also, if a player cannot make a move, they lose the game.
Return True
if and only if Alice wins the game, assuming both players play optimally.
Example 1:
Input: 2
Output: true
Explanation: Alice chooses 1, and Bob has no more moves.
Example 2:
Input: 3
Output: false
Explanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves.
Note:
1 <= N <= 1000
题目要求:给出一个数字N,由A和B两个人进行博弈,首先A找出一个能整除N的数X (N%X == 0,0<X<N),然后将N减去X得到一个新的N (N=N-X)交给B进行同样的操作。最后不能找出X的一方输,即N==1时.
解题思路:
首先解析当N为奇数的情况:
(odd:奇数 even:偶数)
奇数必定是两个奇数的相乘的积。
N为偶数的情况:
所以,N要减去的X,必定是自己的一个因子(N%X == 0),N减去X后的情况如下:
当N为奇数, 时:
当N为偶数,且时:
√
√
当N为偶数,且时:
√
获胜思路:
每次A都将一个为奇数的N留给B,B必定只能返回一个偶数给A(公式1),直到最后将1给B,B输。
若要将奇数留给B,则公式2、4、6满足,结合起来可有一个必赢的方法:N = N -1。
所以,如果首次给的数N为偶数,则A赢,反之,B赢。
代码:
class Solution {
public boolean divisorGame(int N) {
if(N%2==0)
return true;
return false;
}
}