📌  相关文章
📜  通过移除给定的 N 张牌中的最后一张,找出赢得游戏的玩家

📅  最后修改于: 2021-10-25 06:47:16             🧑  作者: Mango

给定两个整数NK ,其中N表示游戏开始时存在的牌总数, K表示单回合可以移除的最大牌数。两名玩家AB轮流取出最多K张牌,从玩家A开始一张一张。取出最后一张牌的玩家为赢家。任务是检查A是否可以赢得比赛。如果发现是真的,打印“A”作为答案。否则,打印‘B’

例子:

方法:这里的想法是观察,每当N % (K + 1) = 0 的值时A将永远无法赢得比赛。否则A总是赢得比赛。
证明:

因此,我们的想法是检查N % (K + 1)是否等于 0。如果发现是真的,打印 B 作为获胜者。否则,打印 A 作为获胜者。
下面是上述方法的实现:

C++
// C++ Program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to check which
// player can win the game
void checkWinner(int N, int K)
{
    if (N % (K + 1)) {
        cout << "A";
    }
    else {
        cout << "B";
    }
}
 
// Driver code
int main()
{
 
    int N = 50;
    int K = 10;
    checkWinner(N, K);
}


Java
// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
 
// Function to check which
// player can win the game
static void checkWinner(int N, int K)
{
    if (N % (K + 1) > 0)
    {
        System.out.print("A");
    }
    else
    {
        System.out.print("B");
    }
}
 
// Driver code
public static void main(String[] args)
{
    int N = 50;
    int K = 10;
     
    checkWinner(N, K);
}
}
 
// This code is contributed by Amit Katiyar


Python3
# Python3 program to implement
# the above approach
 
# Function to check which
# player can win the game
def checkWinner(N, K):
 
    if(N % (K + 1)):
        print("A")
    else:
        print("B")
 
# Driver Code
N = 50
K = 10
 
# Function call
checkWinner(N, K)
 
# This code is contributed by Shivam Singh


C#
// C# program to implement
// the above approach
using System;
 
class GFG{
 
// Function to check which
// player can win the game
static void checkWinner(int N, int K)
{
    if (N % (K + 1) > 0)
    {
        Console.Write("A");
    }
    else
    {
        Console.Write("B");
    }
}
 
// Driver code
public static void Main(String[] args)
{
    int N = 50;
    int K = 10;
     
    checkWinner(N, K);
}
}
 
// This code is contributed by Amit Katiyar


Javascript


输出:
A

时间复杂度: O(1)
辅助空间: O(1)