给定长度为N的二进制字符串str以及两个整数A和B ,使得0≤A 。的任务是计数操作的最小数目的字符串,使得它给出10 A作为剩余部分在由10 B划分的。一个运算意味着将1更改为0或将0更改为1 。
例子:
Input: str = “1001011001”, A = 3, B = 6
Output: 2
The string after 2 operations is 1001001000.
1001001000 % 106 = 103
Input: str = “11010100101”, A = 1, B = 5
Output: 3
方法:为了使数字除以10 B时得到10 A的余数,字符串的最后B位必须为0 ,但从第(A + 1)位起的数字应为1 。因此,请检查字符串的最后B个数字是否满足上述条件,并为每个数字不匹配将计数增加1。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the minimum number
// of operations on a binary string such that
// it gives 10^A as remainder when divided by 10^B
int findCount(string s, int n, int a, int b)
{
// Initialize result
int res = 0;
// Loop through last b digits
for (int i = 0; i < b; i++) {
if (i == a)
res += (s[n - i - 1] != '1');
else
res += (s[n - i - 1] != '0');
}
return res;
}
// Driver code
int main()
{
string str = "1001011001";
int N = str.size();
int A = 3, B = 6;
cout << findCount(str, N, A, B);
return 0;
}
Java
// Java implementation of the approach
import java.util.*;
class GFG
{
// Function to return the minimum number
// of operations on a binary string such that
// it gives 10^A as remainder when divided by 10^B
static int findCount(String s, int n, int a, int b)
{
// Initialize result
int res = 0;
char []s1 = s.toCharArray();
// Loop through last b digits
for (int i = 0; i < b; i++)
{
if (i == a)
{
if (s1[n - i - 1] != '1')
res += 1;
}
else
{
if (s1[n - i - 1] != '0')
res += 1 ;
}
}
return res;
}
// Driver code
static public void main (String []args)
{
String str = "1001011001";
int N = str.length() ;
int A = 3, B = 6;
System.out.println(findCount(str, N, A, B));
}
}
// This code is contributed by ChitraNayal
Python3
# Python 3 implementation of the approach
# Function to return the minimum number
# of operations on a binary string such that
# it gives 10^A as remainder when divided by 10^B
def findCount(s, n, a, b):
# Initialize result
res = 0
# Loop through last b digits
for i in range(b):
if (i == a):
res += (s[n - i - 1] != '1')
else:
res += (s[n - i - 1] != '0')
return res
# Driver code
if __name__ == '__main__':
str = "1001011001"
N = len(str)
A = 3
B = 6
print(findCount(str, N, A, B))
# This code is contributed by
# Surendra_Gangwar
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the minimum number
// of operations on a binary string such that
// it gives 10^A as remainder when divided by 10^B
static int findCount(string s, int n, int a, int b)
{
// Initialize result
int res = 0;
// Loop through last b digits
for (int i = 0; i < b; i++)
{
if (i == a)
{
if (s[n - i - 1] != '1')
res += 1;
}
else
{
if (s[n - i - 1] != '0')
res += 1 ;
}
}
return res;
}
// Driver code
static public void Main ()
{
string str = "1001011001";
int N = str.Length ;
int A = 3, B = 6;
Console.WriteLine(findCount(str, N, A, B));
}
}
// This code is contributed by AnkitRai01
Javascript
输出:
2
时间复杂度: O(N)
辅助空间: O(N)
如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。