Given a binary String which represents the target state. Minimum number of flips needed to convert a same size Binary String (with all 0’s) to target state. A flip also causes all the right bits to be flipped.
e.g.
Input : 00101
(Represents Target)
Output : 3
Explanation :
00000 -> 00111 -> 00100 -> 00101
bitset::flip() in C++ STL bitset::flip() is a built-in STL in C++ which flips the bits. If no parameter is passed in the function, then it flips all the bit values converting zeros to ones and ones to zeros. If a parameter position is passed, it flips the bit at the position only.
Sometimes it is required to inverse the bits i.e., 0's to 1's ( zeros to ones) and 1's to 0's (ones to zeros). Here are there few ways by which we can inverse the bits in Python. 1) Using Loops: By iterating each and every bit we can change the bit 1 to bit 0 and vice-versa.
Two observations:
Flips are commutative. You'll get the same result regardless of what order you do them in.
At some point you have to flip the most significant bit that doesn't match
This gives us a handy greedy argument. We will always get the optimal solution by flipping the leftmost bit that needs to be flipped. At some point we have to flip that bit, and the order doesn't matter so we might as well do it first.
Implementing this to be O(N)
can be tricky - if we flip everything naively we end up with an O(N)
flip which gives an O(N^2)
solution. We can note that in determining the true value of the current bit, we only care about the number of flips that have already occurred. If this number is odd then the value of that bit is flipped. Otherwise it is unchanged.
We can then make a final observation to make life a lot easier:
Pseudocode:
result = 0
// most to least significant
for bit in bits:
if result%2 == 0:
if bit != 0: result += 1
else:
if not bit != 0: result += 1
print(result)
And to be more succinct:
bits = [0, 0, 1, 0, 1]
result = 0
for bit in bits: result += (result%2)^bit
print(result)
Output:
3
Input : 00101 (Represents Target) Output : 3 Explanation : 00000 -> 00111 -> 00100 -> 00101
static int minFlip(String arr) {
String s = "00000";
int i;
char[] original = s.toCharArray();
char[] bits = arr.toCharArray();
int result = 0;
for (i = 0; i < bits.length;) {
if (bits[i] != original[i]) {
for (int j = i; j < original.length; j++) {
if (original[j] == '0') {
original[j] = '1';
} else {
original[j] = '0';
}
}
result++;
}
i++;
}
return result;
}
Thanks, @Primusa for the answer. Below is the code in Java for @Primusa 's answer:
public static int getFlipsCount(String s) {
int result = 0;
int[] arr = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
arr[i] = Integer.valueOf(s.charAt(i) + "");
}
for (int i = 0; i < arr.length; i++) {
result += (result % 2) ^ arr[i];
}
return result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With