LeetCode 43. Multiply Strings

本文介绍了一种处理任意精度大数乘法的方法,通过字符串表示大数,并使用逐位相乘再累加的方式实现两个大数的乘法运算。文章提供了一个具体的C++实现示例,展示了如何将乘法过程分解为类似于加法步骤的操作。

Given two numbers represented as strings, return multiplication of the numbers as a string.

Note: The numbers can be arbitrarily large and are non-negative.


Separate the steps of multiple. It is the same as addition.

for example:

"99" * "99"  -> can be stored in a vector as : {8, 17, 10, 1} // the index is the index addition of both strings index.

The only case needs special care is: the result string shouldn’t start with '0'.... and the "0" result case.

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

string multiply(string num1, string num2) {
    if(num1.size() == 0) return num2;
    if(num2.size() == 0) return num1;
    int m = num1.size();
    int n = num2.size();
    vector<int> res(m + n, 0);
    for(int i = m - 1; i>= 0; --i) {
        for(int j = n - 1; j >= 0; --j) {
            int tmp = (num1[i] - '0') * (num2[j] - '0');
            res[i + j + 1] += tmp % 10;
            res[i + j] += tmp / 10;
        }
    }
    for(int i = m + n - 1; i >= 1; --i) {
        res[i-1] += res[i] / 10;
        res[i] = res[i] % 10;
    }
    string result = "";
    int i = 0;
    while(i < m + n && res[i] == 0) {
        i++;
    }
    while(i < n + m) {
        result = result + to_string(res[i]);
        i++;
    }
    return result.size() == 0 ? "0" : result;  // handle the "0" result case.
}

int main(void) {
    string res = multiply("99", "99");
    cout << res << endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值