码迷,mamicode.com
首页 > 其他好文 > 详细

43. Multiply Strings

时间:2016-03-08 23:30:18      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:

string multiply(string num1, string num2) {
    if (num1 == "0" || num2 == "0") return "0";
    int sa = num1.size();
    int sb = num2.size();
    vector<int> temp(sa + sb, 0);
    for (int i = sa - 1; i >= 0; i--) {
        int a = num1[i] - ‘0‘;
        for (int j = sb - 1; j >= 0; j--) {
            int b = num2[j] - ‘0‘;
            int product = a*b; 
            int carry = (temp[j + i + 1] + product) / 10;
            temp[j + i + 1] = (temp[j + i + 1]+product) % 10;
            int x = 0;
            while (carry) {
                int p = temp[j + i - x] + carry;
                temp[j + i - x] = p % 10;
                carry = p / 10;
                x++;
            }
        }
    }
    while (temp[0] == 0) temp.erase(temp.begin());
    string res;
    for (int i = 0; i < temp.size(); i++) {
        res += to_string(temp[i]);
    }
    return res;
}

43. Multiply Strings

标签:

原文地址:http://www.cnblogs.com/hustlx/p/5255722.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!