Leetcode 3232. Find if Digit Game Can Be Won
You are given a game where a two-player game starts with a positive integer n
. The players take turns performing the following operation: subtract from n
the largest power of 2 less than or equal to n
. The player who cannot make a move loses the game. You need to determine if the starting player can force a win given that both players play optimally.
n
?
1 <= n <= 10^9
.true
if the starting player can force a win; otherwise, return false
.To determine if the starting player can force a win, we need to observe the pattern that occurs as powers of 2 are subtracted from n
.
n
, we need to determine the largest power of 2 less than or equal to n
. This can be done using bitwise operations.n
is a power of 2, the second player always wins, because the first player will reduce n
to 0 in their turn.An efficient approach:
n
is found to be of the form n = 2^k
, the first player always loses.n
is not a power of 2, the first player has a strategy to make it 2^k
in subsequent moves.We can achieve this reasoning with the following implementation.
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
bool canWinDigitGame(int n) {
return (n & (n - 1)) != 0;
}
int main() {
int n;
cout << "Enter the number: ";
cin >> n;
if(canWinDigitGame(n)) {
cout << "Starting player can force a win." << endl;
} else {
cout << "Starting player cannot force a win." << endl;
}
return 0;
}
The function canWinDigitGame
checks if n
is a power of 2:
(n & (n - 1))
is 0
if and only if n
is a power of 2. This is because powers of 2 have only one bit set in their binary representation.true
if the result is non-zero, meaning n
is not a power of 2 and the first player can force a win.n
is a power of 2 using the bit manipulation trick is O(1). This is because the operation involves just a couple of bitwise operations, and these are constant-time operations.This solution is optimal and provides quick determination of the winning strategy for the starting player.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?