首页 > 解决方案 > 为什么 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];
    }
}

标签: c++

解决方案


我认为问题在于您只处理一个查询。但是您的代码似乎应该处理多个查询。您可以将所有代码放在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
    }
}

推荐阅读