📜  求给定骰子输出序列时掷骰子的玩家数

📅  最后修改于: 2021-09-24 05:02:52             🧑  作者: Mango

给定一个字符串S和一个数字X 。有M 个玩家在掷骰子。玩家不断掷骰子,直到得到X以外的数字。在字符串S 中,S[i] 表示第 i掷骰子的数字。任务是找到M请注意S中的最后一个字符永远不会是X
例子:

方法:在字符串迭代并计算不是X的字符。不是X的字符数将是玩家数。
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the number of players
int findM(string s, int x)
{
 
    // Initialize cnt as 0
    int cnt = 0;
 
    // Iterate in the string
    for (int i = 0; i < s.size(); i++) {
 
        // Check for numbers other than x
        if (s[i] - '0' != x)
            cnt++;
    }
    return cnt;
}
 
// Driver code
int main()
{
    string s = "3662123";
    int x = 6;
    cout << findM(s, x);
 
    return 0;
}


Java
// Java implementation of the approach
import java.util.*;
 
class GFG
{
 
// Function to return the number of players
static int findM(String s, int x)
{
 
    // Initialize cnt as 0
    int cnt = 0;
 
    // Iterate in the string
    for (int i = 0; i < s.length(); i++)
    {
 
        // Check for numbers other than x
        if (s.charAt(i) - '0' != x)
            cnt++;
    }
    return cnt;
}
 
// Driver code
public static void main(String args[])
{
    String s = "3662123";
    int x = 6;
    System.out.println(findM(s, x));
 
}
}
 
//This code is contributed by
// Surendra_Gangwar


Python3
# Python 3 implementation of the approach
 
# Function to return the number of players
def findM(s, x):
     
    # Initialize cnt as 0
    cnt = 0
 
    # Iterate in the string
    for i in range(len(s)):
         
        # Check for numbers other than x
        if (ord(s[i]) - ord('0') != x):
            cnt += 1
 
    return cnt
 
# Driver code
if __name__ == '__main__':
    s = "3662123"
    x = 6
    print(findM(s, x))
     
# This code is contributed by
# Surendra_Gangwar


C#
// C# implementation of the approach
using System;
 
class GFG
{
 
// Function to return the number of players
static int findM(String s, int x)
{
 
    // Initialize cnt as 0
    int cnt = 0;
 
    // Iterate in the string
    for (int i = 0; i < s.Length; i++)
    {
 
        // Check for numbers other than x
        if (s[i] - '0' != x)
            cnt++;
    }
    return cnt;
}
 
// Driver code
public static void Main()
{
    String s = "3662123";
    int x = 6;
    Console.Write(findM(s, x));
}
}
 
// This code is contributed by
// mohit kumar


PHP


Javascript


输出:
5

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程