- 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

# Check if two binary strings can be made equal by swapping 1s occurring before 0s

In this article, we will be discussing an intriguing problem related to string manipulation and binary numbers in C++. The problem we will be tackling is "Check if two binary strings can be made equal by swapping 1s occurring before 0s". This problem is a great way to enhance your understanding of strings, binary numbers, and algorithmic thinking.

## Problem Statement

The task is to determine if two binary strings can be made equal by swapping 1s that occur before 0s in the strings.

## C++ Solution Approach

The approach to solve this problem is to keep track of the number of 1s and 0s in both strings. Two binary strings can be made equal by swapping 1s before 0s if and only if both strings have the same number of 1s and 0s.

### Example

Here's the C++ code that implements this solution −

#include <iostream> #include <string> using namespace std; bool canBeMadeEqual(string str1, string str2) { int count1s_str1 = 0, count0s_str1 = 0; int count1s_str2 = 0, count0s_str2 = 0; for (char c : str1) { if (c == '1') { count1s_str1++; } else { count0s_str1++; } } for (char c : str2) { if (c == '1') { count1s_str2++; } else { count0s_str2++; } } return count1s_str1 == count1s_str2 && count0s_str1 == count0s_str2; } int main() { string str1 = "1100"; string str2 = "1010"; bool result = canBeMadeEqual(str1, str2); cout << (result ? "The binary strings can be made equal." : "The binary strings cannot be made equal.") << endl; return 0; }

### Output

The binary strings can be made equal.

## Explanation with a Test Case

Let's consider the binary strings "1100" and "1010".

When we pass these strings to the canBeMadeEqual function, it counts the number of 1s and 0s in both strings.

In the string "1100", there are 2 ones and 2 zeros. In the string "1010", there are also 2 ones and 2 zeros.

Since the number of 1s and 0s in both strings is equal, the function returns true, indicating that the strings can be made equal by swapping 1s before 0s.

## Conclusion

This problem presents a great way to apply knowledge of string manipulation and binary numbers to solve a complex problem in C++. It's an excellent problem to practice your C++ coding skills and to understand how to work with binary numbers in string format.