- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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
Advertisements