Leetcode Multiply Strings

Leetcode Multiply Strings 相关代码,本处同时可以做为相加时的算法,相关代码如下:

#include<iostream>
#include<string>

/*
 * We use the recursive algorithm to solve this proble. We can conclued that
 * the number with more digits can be construct by the less.
 */
using namespace std;
class Solution {
public:
    string multiply(string num1, string num2) {
        int len1 = num1.length();
        int len2 = num2.length();
        if (len1 == 0 || len2 == 0 || num1 == "0" || num2 == "0") {
            return "0";
        }
        len1 --;
        len2 --;
        string pre = "";
        string curent = "";
        string re = "";
        int tmp;
        int carry = 0;
        int value = 0;
        char digit;
        for (int i = len2; i >= 0; i --) {
            curent = pre;
            pre = pre + "0";
            value = num2[i] - '0';
            carry = 0;
            for (int j = len1; j >= 0; j --) {
                tmp = value * (num1[j] - '0') + carry;
                digit = tmp % 10 + '0';
                carry = tmp / 10;
                curent = digit + curent;
            }
            if (carry != 0) {
                curent = to_string(carry) + curent;
            }
            re = add(re, curent);
        }
        return re;
    }

    string add(string num1, string num2) {
        int len1 = num1.length();
        int len2 = num2.length();
        if (len1 == 0) {
            return num2;
        }
        if (len2 == 0) {
            return num1;
        }
        int carry = 0;
        string re = "";
        char digit;
        int tmp;
        len1 = len1 - 1;
        len2 = len2 - 1;
        while (len1 >= 0 && len2 >= 0) {
            tmp = (num1[len1] - '0') + (num2[len2] - '0') + carry;
            digit = tmp % 10 + '0';
            re = digit + re;
            carry = tmp / 10;
            len1 --;
            len2 --;
        }
        while (len1 >= 0) {
            tmp = (num1[len1] - '0') + carry;
            digit = tmp % 10 + '0';
            re = digit + re;
            carry = tmp / 10;
            len1 --;
        }
        while (len2 >= 0) {
            tmp = (num2[len2] - '0') + carry;
            digit = tmp % 10 + '0';
            re = digit + re;
            carry = tmp / 10;
            len2 --;
        }
        if (carry) {
            re = to_string(carry) + re;
        }
        return re;
    }
};

// Sample input: ./a.out argv1
int main(int argc, char* argv[]) {
    Solution so;
    string re = so.multiply(argv[1], argv[2]);
    cout<<"result: "<<re<<endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值