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

43. Multiply Strings

时间:2015-11-02 17:00:09      阅读:174      评论: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.

思路:

利用竖式的思想,进行乘法运算。

 

        3    4

*      1    3

——————

       9      12

3     4

——————

3     13     12

 

再处理进位:

3 13 12 - > 3 14 2 -> 4 4 2

class Solution {
public:
    string multiply(string num1, string num2) {
        reverse(num1.begin(), num1.end());
        reverse(num2.begin(), num2.end());
        int carry = 0;
        string result;
        int len1 = num1.length();
        int len2 = num2.length();
        int resLen = len1+len2-1;
        for(int resPos = 0; resPos<resLen;++resPos) //indicate the pos of the result
        {
            int sum = 0;
            for(int i = max(0,resPos-len2+1); i < len1; ++i) //traverse the digit of num1
            {
                int j = resPos-i; //indicate the pos of num2
                if(j < 0) break;
                sum += (num1[i]-0)*(num2[j]-0);
            }
            sum += carry;
            result.push_back(sum % 10+0);
            carry = sum/10;
        }
        
        while(carry > 0)
        {
            result.push_back(carry % 10+0);
            carry /= 10;
        }
        reverse(result.begin(), result.end());
        if(result.find_first_not_of(0) == string::npos) return "0";//排除全0的情况
        else return result;
    }
};

 

43. Multiply Strings

标签:

原文地址:http://www.cnblogs.com/qionglouyuyu/p/4930350.html

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