Sunday, 27 December 2020

Minimum flips required to get given binary String.

Given a string S, the task is to find minimum flips required to convert an initial binary string consisting of only zeroes to S where every flip of a character flips all succeeding characters as well.

Input: S = “01011”
Output: 3
Explanation:
Initial String – “00000”
Flip the 2nd bit – “01111”
Flip the 3rd bit – “01000”
Flip the 4th bit – “01011”
Total Flips = 3
Input: S = “01001”
Output: 3
Explanation:
Initial String – “00000”
Flip the 2nd bit – “01111”
Flip the 3rd bit – “01000”
Flip the 5th bit – “01001”
Total Flips = 3

Source Code:

public class FlipDigitsOfStringToGetTarget {

public static void main(String[] args) {

String target="01011";
int n=target.length();
System.out.print("Minimum flips required: "+minFlips(target,n));

}
public static int minFlips(String target,int n)
{
int count=0;
char curr='1';

for(int i=0;i<n;i++)
{
char ch=target.charAt(i);

if(ch==curr)
{
++count;
curr=(char)(48+(curr%2));
}
}
return count;
}

}

No comments:

Post a Comment

Random password generator in Java

       Random password generator in Java Source code: mport java.io.*; import java.util.*; public class Main { public static void main(Str...