我一开始提交了一段这样的代码,在本地运行正常,没想到报错 WA : read ASCII 0 ,expect xxx:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
// big num add
string a, b, ans;
int sizea, sizeb;
void add(){
int carry = 0;
int i = 0, j = 0, k = 0;
while (i < sizea || j < sizeb || carry) {
int digit1 = i < sizea ? a[i] - 48 : 0;
int digit2 = j < sizeb ? b[j] - 48 : 0;
int sum = digit1 + digit2 + carry;
ans[k++] = (sum % 10) + '0';
carry = sum / 10;
i ++;
j ++;
}
}
int main(){
cin >> a >> b;
sizea = a.length();
sizeb = b.length();
ans.resize(max(sizea, sizeb) + 1);
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
add();
reverse(ans.begin(), ans.end());
cout << ans << endl;
return 0;
}
添加下面一个函数去除倒转字符串前的 ASCII 0 程序才得以运行:
string remove(string str) {
while (!str.empty() && str[0] == '\0') {
str.erase(str.begin());
}
return str;
}
// ...
cout << remove(ans) << endl;