Minimum number of operations on a binary string such that it gives 10^A as remainder when divided by 10^B
Given a binary string str of length N and two integers A and B such that 0 ? A < B < n. The task is to count the minimum number of operations on the string such that it gives 10A as remainder when divided by 10B. An operation means changing 1 to 0 or 0 to 1.
Examples:
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
Approach: In order for the number to give 10A as remainder when divided by 10B, the last B digits of the string has to be 0 except the digit at (A + 1)th position from the last which should be 1. Therefore, check the last B digits of the string for the above condition and increase the count by 1 for each mismatch of digit.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findCount(string s, int n, int a, int b)
{
int res = 0;
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;
}
int main()
{
string str = "1001011001" ;
int N = str.size();
int A = 3, B = 6;
cout << findCount(str, N, A, B);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int findCount(String s, int n, int a, int b)
{
int res = 0 ;
char []s1 = s.toCharArray();
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;
}
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));
}
}
|
Python3
def findCount(s, n, a, b):
res = 0
for i in range (b):
if (i = = a):
res + = (s[n - i - 1 ] ! = '1' )
else :
res + = (s[n - i - 1 ] ! = '0' )
return res
if __name__ = = '__main__' :
str = "1001011001"
N = len ( str )
A = 3
B = 6
print (findCount( str , N, A, B))
|
C#
using System;
class GFG
{
static int findCount( string s, int n, int a, int b)
{
int res = 0;
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;
}
static public void Main ()
{
string str = "1001011001" ;
int N = str.Length ;
int A = 3, B = 6;
Console.WriteLine(findCount(str, N, A, B));
}
}
|
Javascript
<script>
function findCount(s, n, a, b)
{
var res = 0;
for ( var i = 0; i < b; i++)
{
if (i == a)
res += (s[n - i - 1] != '1' );
else
res += (s[n - i - 1] != '0' );
}
return res;
}
var str = "1001011001" ;
var N = str.length;
var A = 3, B = 6;
document.write(findCount(str, N, A, B));
</script>
|
Time Complexity: O(N )
Auxiliary Space: O(1)
Last Updated :
30 May, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...