Binary Swap

You are given two binary strings A and B of equal length. You have a type of operation in which you can swap any two elements of string B. Your task is to find the minimum number of operations required to convert string B into string A. If it is not possible, print -1.

Example:

Input:  A = "1110", B = "1101"
Output: 1

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int binarySwap(string Astring B)
{
    if (A.size() != B.size())
        return -1;
    else
    {
        int cnt = 0;
        int cnt01 = 0cnt02 = 0;
        for (int i = 0i < A.size(); i++)
        {
            if (A[i] != B[i])
                cnt++;
            if (A[i] == '0')
                cnt01++;
            if (B[i] == '0')
                cnt02++;
        }
        if (cnt01 != cnt02)
            return -1;
        else
            return cnt / 2;
    }
}
int main()
{
    string A = "1110"B = "1101";

    cout << binarySwap(AB<< "\n";

    return 0;
}


No comments:

Post a Comment