
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- 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
- Program to find a good string from a given string in Python
- Program to find minimum string size that contains given substring in Python
- Finding minimum flips in a binary string using JavaScript
- Minimum swaps required to make a binary string alternating in C++
- Python - Check if a given string is binary string or not
- The best way to hide a string in binary code in C++?
- Find the direction from given string in C++
- Converting string to a binary string - JavaScript
- JavaScript Program to Find Lexicographically minimum string rotation
- Minimum number of operations required to sum to binary string S using C++.
- Code to construct an object from a string in JavaScript
- Construct Binary Tree from String in C++

Advertisements