SIGABRT in BINFUN - please help

#include <bits/stdc++.h>
#include <string>
#include <math.h>

using namespace std;

#define rep(i, n) for(int i = 0; i < n; i++)
#define rev_rep(i, n) for(int i = n - 1; i > 0; i--)
#define pb push_back

vector<int> arr;

string to_binary(int n){
    string r = "";
    while(n != 0){
        r = (n % 2 == 0 ? "0" : "1") + r;
        n /= 2;
    }
    return r;
}

int to_int(int n){
    int response = 0;
    int i = 0;
    while(n){
        response += (n % 10) * pow(2, i);
        i++;
        n /= 10;
    }
    return response;
}

void bin_concat(int x, int y){
    string x_plus_y = to_binary(x) + to_binary(y);
    string y_plus_x = to_binary(y) + to_binary(x);
    cout << to_int(stoi(x_plus_y)) - to_int(stoi(y_plus_x));
}

void solve(){
    int min_b = *min_element(arr.begin(), arr.end());
    int max_b = *max_element(arr.begin(), arr.end());
    bin_concat(min_b, max_b);
}

int main() {
	ios_base::sync_with_stdio (false);
	cin.tie (NULL);
	cout.tie (NULL);
	int t, n;
	cin >> t;
	while (t--) {
	    cin >> n;
	    int temp;
	    rep(i, n) { 
	        cin >> temp;
	        arr.pb(temp);
	    }
	    solve();
	    cout << "\n";
	    arr.clear();
	}
}

link of submission: https://www.codechef.com/viewsolution/36162825
problem: https://www.codechef.com/problems/BINFUN

Please either format your code or (better!) link to your submission - the forum software has mangled it and it won’t compile! :slight_smile:

Also - what Problem are you trying to solve? :slight_smile:

1 Like

not sure about algorithm, but i want to find the reason for SIGABRT error, added links.

The reason is when you do stoi(x_plus_y), it can give integer with more than 31 bits, hence use stoll.
Also to_int function will give error for concatenated numbers, use long long there as well.

1 Like

@codemastercpp beat me to it :slight_smile:

Here’s a concrete test input that causes your solution to crash:

1
2
536870912 536870912
5 Likes

it’s still not working with this.

Neither int nor long can hold a 60-digit decimal integer.

Just skip converting x_plus_y and y_plus_x to decimal before converting to binary and convert directly, as binary strings, to decimal i.e. do the inverse of your to_binary function.

2 Likes

thank you so much. :blush: :pray:

1 Like