Also the number n-2^k has to be as beautiful as n (The beauty of a number depends on the number of one's in its binary representation). The player loses the game when he can't select any such k.
Given the initial number n, determine which player will win the game if both players play optimally. n > 0 and n <= 10^9.
----------------------------------------------------------------------------------------
Look
at the number as a binary string. Then all valid moves are of the form replace an instance of "10" with "01". Moreover, all such exchanges are also valid moves.
This is because subtracting 2^k has the effect of flipping all bits between k and the first index starting or after k that is
1. Therefore you can only select a k where s_k is 0 and s_{k+1} is 1, otherwise you will change the beauty of the string.
Since each 0 character needs to move past each 1 character and each move makes one such exchange, the number of moves for the
game is fixed (there are no bad moves). The winner is dependent on the parity of the inversion count in the binary representation of n; with first player winning when it is odd.
----------------------------------------------------------------------------------------
****************************************************************************************
Below is some method I don't like :
For the input n, in binary format "100101", the first player, A will lose the game, and the second player B, will win. BC, A can change n to "100011"
or "10101", at the first round. For "100011", B can easily win the game. For "10101", B can win the game by change it to "10011".
We can change the model of this problem to the following. Considering there are several buckets, in each of them, there are some balls (means the number
of '0'), or, nothing. For instance, "100101" can be represented by 2 buckets, the first bucket has 2 balls and second has 1. Then, for each player, he can pick one bucket and move one ball from the this bucket (ith one) to the (i - 1)th bucket. Of cause, we
can only move the ball forward. The guy that moves the last ball win the game.
int willFirstWin(int result[], int len) {
int i = 1;
while (i < len) {
if (result[i] > 0)
break;
i++;
}
if (i == len)
return -1;
for (i = 1; i < len; i++) {
if (result[i] == 0)
continue;
result[i - 1]++;
result[i]--;
if (willFirstWin(result, len))
return 0;
result[i - 1]--;
result[i]++;
}
return -1;
}