我正在尝试从数组元素中形成最大数。下面给出的我的实现在某些情况下工作正常,而在其他一些情况下它给出错误 “来自 abort(3) (SIGABRT) 的中止信号”。为什么?帮帮我!
#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;
}
对于以下情况,我的代码给出了错误
4 //size of array 54 546 548 60 //elements of array
最佳答案
这是由于 stoi
功能。这不适用于非常大的数字。
对于 string
到 int
的转换,请尝试以下方法。
手动将 string
转换为 int
的算法:
int x = 0; // may take long long
for(int i = 0; i < s.length(); i++)
x = x * 10 + s[i] - '0';
变量x
将存储讨论中的字符串的整数值。
关于c++ - "Abort signal from abort(3) (SIGABRT)"。为什么只针对某些情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50459604/