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

43. Multiply Strings 字符串表示的大数乘法

时间:2016-03-06 12:35:26      阅读:154      评论: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.

 

string multiply(string& num, char ch){
    int n = ch - 0;
    string s;
    int carry = 0;
    int x;
    for(int i=num.size()-1; i>=0; i--){
        x = (num[i]-0) * n + carry;
        carry = x/10;
        s.insert(s.begin(), x%10+0); 
    }
    if (carry>0) {
        s.insert(s.begin(), carry+0);
    }
    return s;
}

string strPlus(string& num1, string& num2) {
    string s;
    int carry=0;
    int x;
    int n1 = num1.size(); 
    int n2 = num2.size(); 
    
    int i, j;
    for(i=n1-1, j=n2-1; i>=0 || j>=0; i--, j--){
        int x1 = i>=0 ?  num1[i]-0 : 0;
        int x2 = j>=0 ?  num2[j]-0 : 0;
        x = x1 + x2 + carry; 
        carry = x/10;
        s.insert(s.begin(), x%10+0);
    }
    if (carry>0) {
        s.insert(s.begin(), carry+0);
    }
    return s;
}

string multiply(string num1, string num2) {

    if (num1.size()<=0 || num2.size()<=0) return "";

    int shift=0;
    string result="0";
    for (int i=num1.size()-1; i>=0; i--) {
        string s = multiply(num2, num1[i]);        
        for(int j=0; j<shift; j++){
            s.insert(s.end(), 0);
        }
        result = strPlus(result, s);
        shift++;
    }
    //check if it is zero
    if (result[0]==0) return "0";
    return result;
}

 

43. Multiply Strings 字符串表示的大数乘法

标签:

原文地址:http://www.cnblogs.com/argenbarbie/p/5246792.html

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