# Find the last player to be able to flip a character in a Binary String

Welcome to our comprehensive guide on a stimulating algorithmic problem involving binary strings in C++. We will be examining a problem where we need to find the last player who can flip a character in a binary string. This problem is a great exercise for understanding game theory and binary string manipulation.

## Problem Statement

Given a binary string, we have two players who take turns to flip a '1' into a '0'. The player who cannot make a move loses the game. The task is to find out who, between Player 1 and Player 2, will be the last player to be able to flip a character.

## Approach

We will iterate over the binary string, counting the number of '1's. If the number of '1's is even, Player 2 will be the last to flip a '1', as Player 1 always starts the game. If the number of '1's is odd, Player 1 will be the last to flip a '1'.

## C++ Implementation

### Example

Here's the C++ solution for this problem −

#include<bits/stdc++.h>
using namespace std;

string lastPlayer(string s) {
int count = 0;
for (char c : s) {
if (c == '1')
count++;
}
return (count % 2 == 0) ? "Player 2" : "Player 1";
}

int main() {
string s="1101";

cout << "The last player to be able to flip a character is: " << lastPlayer(s) << endl;
return 0;
}


### Output

The last player to be able to flip a character is: Player 1


This program inputs a binary string and outputs the last player who can flip a character.

## Test Case Example

Let's consider an example to clarify this problem and its solution −

Suppose the binary string is "1101".

• We start by counting the number of '1's in the binary string.

• The count of '1's in "1101" is 3, which is an odd number.

• Since the count is odd, Player 1 will be the last to flip a '1'.

• Therefore, the output will be "The last player to be able to flip a character is: Player 1".

## Conclusion

In this C++ guide, we've learned how to determine the last player who can flip a character in a binary string. This problem is an interesting exploration of game theory and binary string manipulation.

Updated on: 17-May-2023

38 Views