ronith
5/31/2018 - 6:45 AM

Rearrange a binary string as alternate x and y occurrences

Given a binary string s and two integers x and y are given. Task is to arrange the given string in such a way so that ‘0’ comes X-time then ‘1’ comes Y-time and so on until one of the ‘0’ or ‘1’ is finished. Then concatenate rest of the string and print the final string. Given : x or y can not be 0 Input : s = "0011" x = 1 y = 1 Output : 0101

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

int main(){
    string s;
    cin >> s;
    long int n = s.size();
    int a = stoi(s);

    int count0=0,count1=0;
    while(n>0){
        if (a%10 == 0)
            count0++;
        else
            count1++;
        a/=10;
        n--;
    }
    s = "";
    while(count0!=0 && count1!=0){
        s.append("0");
        count0--;
        s.append("1");
        count1--;
    }
    while(count0!=0){
        s.append("0");
        count0--;
    }
    while (count1!=0){
        s.append("1");
        count1--;
    }
    cout<<s;
}