I am trying to form largest number from elements of array. My implementation given below is working fine for some cases and for some other its giving error " Abort signal from abort(3) (SIGABRT)" . Why? Help me out!
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int main() {
int t;
cin>>t;
while((t--)>0){
int n;
cin>>n;
int a[n];
string s="";
for(int i=0;i<n;i++){
cin>>a[i];
if(i==0){s+=to_string(a[i]); continue;}
string s1 = s+to_string(a[i]); //sX
string s2 = to_string(a[i])+s; //Xs
if(stoi(s1)>=stoi(s2))s=s1;
else s = s2;
}
cout<<s<<endl;
}
return 0;
}
For the following case my code is giving the error
4 //size of array 54 546 548 60 //elements of array
This is due to the stoi
function. This does not work with a very large number.
For a string
to int
conversion try the following approach.
Algorithm to manually converting a string
to int
:
int x = 0; // may take long long
for(int i = 0; i < s.length(); i++)
x = x * 10 + s[i] - '0';
Variable x
will store the integer value of the string in discussion.