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

Multiply Strings leetcode

时间:2016-01-11 22:07:22      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

Subscribe to see which companies asked this question

 

ACM竞赛常考的大数相乘算法,利用字符串来表示大数字进行计算。

string multiply(string num1, string num2) {
    string num(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 tmp = num[i + j + 1] - 0 + (num1[i] - 0) * (num2[j] - 0) + carry;
            num[i + j + 1] = tmp % 10 + 0;
            carry = tmp / 10;
        }
        num[i] += carry;
    }
    size_t startpos = num.find_first_not_of(0);
    if (startpos != string::npos)
        return num.substr(startpos);
    return "0";
}

 

Multiply Strings leetcode

标签:

原文地址:http://www.cnblogs.com/sdlwlxf/p/5122584.html

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