LeetCode | 43. Multiply Strings(大整数乘法)

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

Note:

The length of both num1 and num2 is < 110.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.

大整数乘法,6ms AC

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

string multiply(string num1, string num2)
{
    //i 和 j 相乘的结果是 res 的 (i+j) 位
    string str_res = "";
    int first = 0;
    int res[300] = {};
    int len1 = num1.length(), len2 = num2.length();
    if(len1 < len2)
        return multiply(num2, num1);
    int a[120] = {};
    int b[120] = {};

    for(int i=0;i<len1;i++)
        a[i] = num1[len1-i-1]-'0';
    for(int i=0;i<len2;i++)
        b[i] = num2[len2-i-1]-'0';

    for(int i=0;i<len1;i++)
    {
        for(int j=0;j<len2;j++)
        {
            res[i+j] += a[i]*b[j];
        }
    }

    for(int i=0;i<len1+len2+2;i++)
    {
        if(res[i] >= 10)
        {
            res[i+1] += res[i]/10;
            res[i] %= 10;
        }
    }

    for(int i=290;i>=0;i--)
        if(res[i] != 0)
        {
            first = i; break;
        }
    for(int i=first;i>=0;i--)
    {
        str_res += res[i]+'0';
    }

    return str_res;
}

int main()
{
    string str1, str2;
    while(cin>>str1>>str2)
    {
        cout<<multiply(str1, str2)<<endl;
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值