Friday, November 18, 2016

Number of flips to make binary string alternate

Given a binary string, that is it contains only 0s and 1s. We need to make this string a sequence of alternate characters by flipping some of the bits, our goal is to minimize the number of bits to be flipped.
Examples
Input : str = “001”
Output : 1
Minimum number of flips required = 1
We can flip 1st bit from 0 to 1 

Input : str = “0001010111”
Output : 2
Minimum number of flips required = 2
We can flip 2nd bit from 0 to 1 and 9th 
bit from 1 to 0 to make alternate 
string “0101010101”.

#include <iostream>
using namespace std;

int numberoftransformsrequired(string a,char expected)
{
int count =0;

for(int i=0;i<a.length();i++){
if(a[i]!=expected)
count++;
if(expected == '1')
expected = '0';
else
expected = '1';
}

return count;
}

int main (){
string a ="1110100001";
cout<<min(numberoftransformsrequired(a,'1'),numberoftransformsrequired(a,'0'));


}

No comments:

Post a Comment

Contributors

Translate