您的位置:首页 > 其它

[LeetCode]Multiply Strings

2015-08-08 23:25 274 查看

题目

Number: 43

Difficulty: Medium

Tags: Math, String

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.

题解

输入两个字符串,

输出一个字符串,为两个字符串的乘积。

模拟乘法。

代码

[code]string multiply(string num1, string num2) {
    string result(num1.size() + num2.size(), '0');
    for(int i = num1.size() - 1; i >= 0; --i)
    {
        int carry = 0;
        for(int j = num2.size() - 1; j >= 0; --j)
        {
            int temp = (result[i + j + 1] - '0') + (num1[i] - '0') * (num2[j] - '0') + carry;
            result[i + j + 1] = temp % 10 + '0';
            carry = temp / 10;
        }
        result[i] += carry;
    }
    size_t startpos = result.find_first_not_of("0");
    if(string::npos != startpos)
        return result.substr(startpos);
    return "0";
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: