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

【Multiply Strings】cpp

时间:2015-06-08 19:23:30      阅读:140      评论: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) {
            const int n1 = num1.size(), n2 = num2.size();
            if ( num1=="0" || num2=="0") return "0";
            vector<char> ret;
            for ( int i=n1-1; i>=0; --i )
            {
                vector<char> local(1,0);                
                int v = 0, carry = 0, curr = 0;
                for ( int j=n2-1; j>=0; --j )
                {
                    v= (num1[i]-0)*(num2[j]-0);
                    carry = v/10;
                    curr = v%10;
                    carry += ((local[0]-0)+curr)/10;
                    curr = ((local[0]-0)+curr)%10;
                    local[0] = curr+0;
                    local.insert(local.begin(), carry+0);
                }
                if (local[0]==0) local.erase(local.begin());
                // cout << string(local.begin(),local.end()) << endl;
                // add zeros
                for ( int z=n1-1; z>i; --z) local.push_back(0);
                // cout << string(local.begin(),local.end()) << endl;
                carry = 0, curr = 0;
                for ( int r=ret.size()-1, l=local.size()-1; r>=0 || l>=0; --r,--l )
                {
                    if ( r>=0 && l>=0 )
                    {
                        curr = (carry+(ret[r]-0)+(local[l]-0))%10;
                        carry = (carry+(ret[r]-0)+(local[l]-0))/10;
                        local[l] = curr+0;
                    }
                    else
                    {
                        curr = (carry+(local[l]-0))%10;
                        carry = (carry+(local[l]-0))/10;
                        local[l] = curr+0;
                    }
                }
                if (carry!=0) { local.insert(local.begin(), carry+0); }
                ret = local;
            }
            return string(ret.begin(),ret.end());
    }
};

tips:

就是一些字符串操作的细节,考虑进位,0这类的细节。

【Multiply Strings】cpp

标签:

原文地址:http://www.cnblogs.com/xbf9xbf/p/4561409.html

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