Maximum Binary String After Change LeetCode solution in C++

1
class Solution {
2
public:
3
string maximumBinaryString(string binary) {
4
int n = binary.size();
5
int z_count = 0; // count the number of zeros
6
int z_index = -1; // index of the leftmost zero that is why we start
7
// iterating from the right
8
for (int i = n - 1; i >= 0; i--) {
9
if (binary[i] == '0') {
10
z_count++;
11
z_index = i;
12
binary[i] = '1'; // changing all occurances to 1
13
}
14
}
15
if (z_index != -1) // to check if there is atleast 1 zero
16
{
17
binary[z_index + z_count - 1] = '0'; // this is the only zero present
18
// -1 because the only zero is also included in zero count
19
}
20
return binary;
21
}
22
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0