Maximize the decimal equivalent by flipping only a contiguous set of 0s
Last Updated :
16 Nov, 2021
Given a binary number in the form of a string, the task is to print a binary equivalent obtained by flipping only one contiguous set of 0s such that the decimal equivalent of this binary number is maximum.
Note: Do not assume any trailing zeroes in the start of the binary number i.e. “0101” is given as “101”.
Examples:
Input: s = “10101”
Output: 11101
Explanation:
Here we can only flip the 2nd character of the string “10101” ( = 21) that will change it to “11101” (= 29). Since we are allowed to flip a continuous subarray, any more flipping will lead to decrease in decimal equivalent.
Input: s = “1000”
Output: 1111
Explanation:
If we flip the continuous characters starting from position 1 till 3 we will get 1111 which is the maximum number possible in 4 bits i.e. 15.
Approach: To solve the problem mentioned above we know that we have to increase the value of the binary equivalent. Therefore, we must increase the number of 1’s at higher position. Clearly, we can increase the value of the number by only flipping the initially occurring zeroes. Traverse the string and flip the first occurrence of zeroes until a 1 occurs, in this case, the loop must break. Print the resultant string.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void flip(string& s)
{
for ( int i = 0; i < s.length(); i++) {
if (s[i] == '0' ) {
while (s[i] == '0' ) {
s[i] = '1' ;
i++;
}
break ;
}
}
}
int main()
{
string s = "100010001" ;
flip(s);
cout << s;
return 0;
}
|
Java
import java.util.*;
class GFG{
static void flip(String s)
{
StringBuilder sb = new StringBuilder(s);
for ( int i = 0 ; i < sb.length(); i++)
{
if (sb.charAt(i) == '0' )
{
while (sb.charAt(i) == '0' )
{
sb.setCharAt(i, '1' );
i++;
}
break ;
}
}
System.out.println(sb.toString());
}
public static void main(String[] args)
{
String s = "100010001" ;
flip(s);
}
}
|
Python3
def flip(s):
s = list (s)
for i in range ( len (s)):
if (s[i] = = '0' ):
while (s[i] = = '0' ):
s[i] = '1'
i + = 1
s = ''.join( map ( str , s))
return s
s = "100010001"
print (flip(s))
|
C#
using System;
class GFG{
static String flip( char []s)
{
for ( int i = 0; i < s.Length; i++)
{
if (s[i] == '0' )
{
while (s[i] == '0' )
{
s[i] = '1' ;
i++;
}
break ;
}
}
return new String(s);
}
public static void Main(String[] args)
{
String s = "100010001" ;
Console.WriteLine(flip(s.ToCharArray()));
}
}
|
Javascript
<script>
function flip(s)
{
for (let i = 0; i < s.length; i++)
{
if (s[i] == '0' )
{
while (s[i] == '0' )
{
s[i] = '1' ;
i++;
}
break ;
}
}
return s.join( "" );
}
let s = "100010001" ;
document.write(flip(s.split( '' )));
</script>
|
Time Complexity: O(|s|)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...