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

Multiply Strings

时间:2016-04-11 18:15:11      阅读:112      评论: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:
    string multiply(string num1, string num2) {
        int len1=num1.length(),len2=num2.length();
        string res(len1+len2,0);
        for(int i=len1-1;0<=i;i--){
            int carry=0;
            for(int j=len2-1;0<=j;j--){
                int tmp=(res[i+j+1]-0)+(num1[i]-0)*(num2[j]-0)+carry;
                res[i+j+1]=tmp%10+0;//各位处理
                carry=tmp/10;
            }
            res[i]+=carry;//最高位处理
        }
         size_t startpos = res.find_first_not_of("0");
         if (string::npos != startpos) {
            return res.substr(startpos);
        }
        return "0";    
    }
};

 

Multiply Strings

标签:

原文地址:http://www.cnblogs.com/wqkant/p/5379071.html

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