Friday, July 2, 2021

Published July 02, 2021 by Anonymous with 0 comment

XOR of very large Binary Numbers in range [L, R]

#include <iostream>

using namespace std;

  

string sub(string s)

{

    int n = s.size();

    for (int i = n - 1; i >= 0; i--) {

        

        

        if (s[i] == '0') {

            s[i] = '1';

        }

        else {

            

            

            

            s[i] = '0';

            break;

        }

    }

    

    return s;

}

  

string ad(string s)

{

    int n = s.size();

  

    int carry = 0;

    for (int i = n - 1; i >= 0; i--) {

        

        

        

        if (s[i] == '1') {

            carry = 1;

            s[i] = '0';

        }

        else {

            

            

            

            

            carry = 0;

            s[i] = '1';

            break;

        }

    }

    

    

    

    if (carry) {

        s = '1' + s;

    }

    return s;

}

  

string xor_finder(string s)

{

    int n = s.size() - 1;

  

    

    

    

    int val = s[n] - '0';

    val = val + (s[n - 1] - '0') * 2;

  

    

    

    if (val == 0) {

        return s;

    }

    else if (val == 1) {

        

        

        s = '1';

        return s;

    }

    else if (val == 2) {

        

        

        return (ad(s));

    }

    else if (val == 3) {

        

        

        s = '0';

        return s;

    }

}

string final_xor(string L, string R)

{

    

    

    while (L.size() != R.size()) {

        L = '0' + L;

    }

    string ans = "";

    for (int i = 0; i < L.size(); i++) {

        

        

        

        if (L[i] == '0' && R[i] == '0') {

            ans += '0';

        }

        else if (L[i] == '0' && R[i] == '1'

                 || L[i] == '1' && R[i] == '0') {

            

            

            

            ans += '1';

        }

        else {

            

            

            

            ans += '0';

        }

    }

    return ans;

}

  

string xorr(string L, string R)

{

    

    L = sub(L);

  

    

    L = xor_finder(L);

  

    

    R = xor_finder(R);

  

    

    string ans = final_xor(L, R);

  

    return ans;

}

  

int main()

{

    

    string L = "10", R = "10000";

  

    

    cout << xorr(L, R) << endl;

    return 0;

}

Adblock test (Why?)


Original page link

Best Cool Tech Gadgets

Top favorite technology gadgets
      edit

0 comments:

Post a Comment