

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ code to find minimum correct string from given binary string
Suppose we have a binary string S with n bits. There are no redundant leading zeroes. We can perform two different operations on S −
Swap any pair of adjacent bits
Replace all "11" with "1"
Let val(S) is decimal representation of S. We have to find minimum correct string, where correct string A is less than another correct string 'B' when val(A) < val(B)
So, if the input is like S = "1001", then the output will be 100, because we can perform the operation like "1001" -> "1010" -> "1100" -> "100".
Steps
To solve this, we will follow these steps −
n := size of S res := a blank string res := res + S[0] for initialize i := 1, when i < n, update (increase i by 1), do: if S[i] is same as '0', then: res := res concatenate "0" return res
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; string solve(string S){ int n = S.size(); string res = ""; res += S[0]; for (int i = 1; i < n; i++){ if (S[i] == '0'){ res += "0"; } } return res; } int main(){ string S = "1001"; cout << solve(S) << endl; }
Input
"1001"
Output
100
- Related Questions & Answers
- Program to find a good string from a given string in Python
- Minimum steps to remove substring 010 from a binary string in C++
- Program to find minimum changes required for alternating binary string in Python
- C++ program to find minimum how many coins needed to buy binary string
- Find the direction from given string in C++
- Program to find minimum string size that contains given substring in Python
- Program to count minimum invalid parenthesis to be removed to make string correct in Python
- Python - Check if a given string is binary string or not
- Finding minimum flips in a binary string using JavaScript
- Converting string to a binary string - JavaScript
- Minimum swaps required to make a binary string alternating in C++
- Construct String from Binary Tree in Python
- Construct Binary Tree from String in C++
- C++ code to find minimum k to get more votes from students
- The best way to hide a string in binary code in C++?
Advertisements