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

Multiply Strings

时间:2015-11-28 01:06:06      阅读:197      评论: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.

class Solution {
public:
    void multiply(string &num1,char digit,string &res,int pos)
    {
        int num1Size = num1.size();
        int c = 0;
        for(int i=num1Size-1;i>=0;i--){
            char tmp  = ((num1[i]-0)*(digit-0) + (res[pos]-0) + c) % 10  + 0 ;
            c =  ((num1[i]-0)*(digit-0) + res[pos]-0 +c ) / 10;
            res[pos] = tmp;
            pos--;
        }
        if(c!=0){
            res[pos] = c + 0;
        }
    }
    string multiply(string num1, string num2) {
        int num1Size = num1.size();
        int num2Size = num2.size();
        int len = num1Size+num2Size;
        string res(len,0);
        int pos = len;
        for(int i=num2Size-1;i>=0;i--){
            multiply(num1,num2[i],res,--pos);
        }
        int i=0,k=0;
        while(i<len && res[i]==0){
            i++;
        }
        if(i==len){
            res="0";
        }else{
            res.erase(res.begin(),res.begin()+i);
        }
        return res;
    }
};

 

Multiply Strings

标签:

原文地址:http://www.cnblogs.com/zengzy/p/5002042.html

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