2020-12-13 09:04

# 为什么这段代码超时了两个点？（c++）

``````读入三个整数，计算三个整数的和。

``````#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
using namespace std;
int a[3][1005], len[3];
string num[3];
int main() {
freopen("abc.in", "r", stdin);
freopen("abc.out", "w", stdout);
for (int i = 0; i < 3; i++) {
cin >> num[i];
}
for (int i = 0; i < 3; i++) {
len[i] = num[i].size();
for (int j = 0; j < len[i]; j++) {
a[i][j] = num[i][len[i] - 1 - j] - '0';
}
}
for (int i = 1; i < 3; i++) {
len[0] = max(len[0], len[i]);
for (int j = 0; j < len[0]; j++) {
a[0][j] += a[i][j];
}
}
for (int j = 0; j < len[0]; j++) {
a[0][j + 1] += a[0][j] / 10;
a[0][j] %= 10;
}
while (a[0][len[0]]) {
a[0][len[0] + 1] += a[0][len[0]] / 10;
a[0][len[0]] %= 10;
}
while (a[0][len[0]]) {
a[0][len[0] + 1] += a[0][len[0]] / 10;
a[0][len[0]] %= 10;
len[0]++;
}
for (int i = len[0] - 1; i >= 0; i--) {
cout << a[0][i];
}
cout << endl;
return 0;
}``````

``````测评信息
================================================

---------------------------

---------------------------

59380248390522737902399703986576270399917236558147138480460326941378838153543659……
38232545435624283942618270827932577950443597448212430922923475416464599289138936……
95201315424599457304371257529133099316698528678680201965238270710142106445034555……

19281410925074647914938923234364194766705936268503977136862207306798554388771715……

---------------------------

---------------------------

================================================

================================================
6``````
• 写回答
• 好问题 提建议
• 关注问题
• 收藏
• 邀请回答

#### 1条回答默认 最新

• Chinesischguy 2020-12-13 14:53
已采纳

第一个while会死循环吧

``````string res;
reverse(s1.begin(), s1.end());//索引0为个位
reverse(s2.begin(), s2.end());
reverse(s3.begin(), s3.end());
if(s1.size()>s2.size())//按长度排序，方便判断while循环
swap(s1,s2);
if(s2.size()>s3.size())
swap(s1,s2);
if(s1.size()>s2.size())
swap(s1,s2);
{
if(idx<s1.size())
{
res.push_back((temp%10)+'0');
}
else if(idx<s2.size())
{
res.push_back((temp%10)+'0');
}
else if(idx<s3.size())
{
res.push_back((temp%10)+'0');
}
else
{