在 C++ 中乘以单个位值

Multiplication by Individual Place Value in C++

我有两个非负数,表示为可能具有不同长度的数字数组,我想将它们相乘而不使用 stoll 转换为字符串,因为这限制了输入大小。

我可以让它在 900 * 9 的情况下工作,但不能在 11 * 11 的情况下工作。

这是我目前拥有的:

  #include <iostream>
  int main() {

    int a[100], b[100], product[200]; // required to use
    int n, m;
    cin >> n >> m;
    for (int i = 0; i < n; i++) {
      cin >> a[i];
    }
    for (int i = 0; i < m; i++) {
      cin >> b[i];
    }

    int temp2 = 0;
    for (int i = 0; i < n; i++) {
      int temp1 = temp2*10; // i think it might be this line that doesn't always work but i don't know what I should change it to
      for (int j = 0; j < m; j++) {
        temp2 = a[i] * b[j] + temp1;
        cout << temp2 << endl;
      }
    }
  }

我在下面的解决方案中修复了您的代码。解决方案存储在 product 数组中,然后移动到名为 solutionvector<int> 中,其中 size 等于最终答案的确切位数,并打印到控制台程序完成后:

#include <iostream>
#include <vector>
using namespace std;

int main() {

    int a[100], b[100], product[200]; // required to use
    for (int i = 0; i < 200; ++i) {
        product[i] = 0;
    }
    int n, m;
    cin >> n >> m;
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    for (int i = 0; i < m; i++) {
        cin >> b[i];
    }

    int lineDigit = 0;
    for (int i = n - 1; i >= 0; i--) {
        int lineSum = 0;
        for (int j = m - 1; j >= 0; j--) {
            int digit = (m - j) + 1;

            int digitProd = a[i] * b[j];
            int tens = digitProd / 10;
            int ones = digitProd % 10;
            product[digit + lineDigit] += ones;
            product[digit + lineDigit + 1] += tens;

            product[digit + lineDigit + 1] += product[digit + lineDigit] / 10;
            product[digit + lineDigit] %= 10;
        }

        ++lineDigit;
    }

    bool foundNonZero = false;
    vector<int> solution;
    for (int i = 199; i >= 2; --i) {
        if (!foundNonZero) {
            if (product[i] != 0) {
                foundNonZero = true;
            }
            else {
                continue;
            }
        }
        solution.push_back(product[i]);
    }

    for (int i = 0; i < solution.size(); ++i) {
        cout << solution[i] << ' ';
    }
    cout << endl;

    system("pause");
}

您的代码中存在几个简单的算术错误。仔细阅读它不会很清楚;继续思考乘法是如何手工完成的,并尝试使逻辑正确。