c++ - 为什么 uva 10106 的答案错误?
问题描述
我正在尝试解决https://vjudge.net/problem/UVA-10106这是一个需要将两个大数相乘的问题。
该代码在我的计算机上运行时显示正确答案,但在线法官给出“错误答案”。
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
string a, b;
cin >> a >> b;
vector<int> c, d;
for (int i = a.size() - 1; i >= 0; i--) {
int z = a[i] - 48;
c.push_back(z);
}
for (int i = b.size() - 1; i >= 0; i--) {
int x = b[i] - 48;
d.push_back(x);
}
if (c.size() > d.size()) {
c.swap(d);
}
int l = c.size() + d.size();
vector<int> s(l, 0);
int carry = 0, sum = 0;
for (int i = 0; i < c.size(); i++) {
int t;
for (int j = 0; j < d.size(); j++) {
sum = c[i] * d[j] + carry + s[i + j];
carry = sum / 10;
s[i + j] = sum % 10;
t = i + j;
sum = 0;
}
if (carry != 0) {
s[t + 1] = carry;
carry = 0;
}
}
for (int i = l - 1; i >= 0; i--) {
if (s[i] != 0) {
break;
}
else {
l--;
}
}
for (int i = l - 1; i >= 0; i--) {
cout << s[i];
}
}
解决方案
我认为问题在于您只处理一个查询。但是您的代码似乎应该处理多个查询。您可以将所有代码放在while
-loop 中,并具有验证输入的额外好处。其次,您不会打印换行符来分隔输出。
像这样的东西可能会起作用:
#include <vector>
#include <string>
int main()
{
std::string a, b;
while (std::cin >> a >> b) // loops as long as there are two strings to read
{
/* Rest of your code goes here */
std::cout << '\n'; //end output of query with new line
}
}
推荐阅读
- serilog - Serilog 仅在一个文件中滚动日志
- reactjs - React-Redux 单击时更改状态
- c++ - 如何从 std::chrono::system_clock::time_point.time_since_epoch().count() 获取 std::chrono::system_clock::time_point?
- java - 联系不在 testRunner 类和条件下的类的最佳方式
- netsuite - 为什么我不能在 SuiteScript 中创建供应商账单?
- git - Git fetch 不会更新到最新提交
- react-router-v4 - 从 auth0 重定向到 netlify 时出错
- c - 创建一个复制 3d 数组内容的函数
- python - Python 值与标头不匹配
- javascript - 如何修复“无法读取 null 的属性‘addEventListener’”错误