标签:
题目:
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这类的细节。
标签:
原文地址:http://www.cnblogs.com/xbf9xbf/p/4561409.html