题目:
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这类的细节。
======================================
第二次过这道题,憋了好久。主要是有个思维误区,认为tmp比ret最多多一位;但是,比如52*4这样的例子,2*4=8 50*4=200就不止一位了。
解决了这个误区,代码AC了。
class Solution { public: string multiply(string num1, string num2) { if ( num1=="0" || num2=="0" ) return "0"; vector<char> ret(num2.size(),'0'); for ( int i=num1.size()-1; i>=0; --i ) { // mupltiply ret vector<int> tmp; int val = 0, carry = 0; for ( int j=num2.size()-1; j>=0; --j ) { val = (num2[j]-'0')*(num1[i]-'0')+carry; tmp.insert(tmp.begin(), val%10); carry = val/10; } if ( carry>0 ) tmp.insert(tmp.begin(), carry); for ( int k=0; k<num1.size()-1-i; ++k ) tmp.push_back(0); // merge tmp & ret while ( tmp.size()>ret.size() ) ret.insert(ret.begin(),'0'); val = 0; carry = 0; for ( int m=tmp.size()-1; m>=0; --m ) { val = (ret[m]-'0') + tmp[m] + carry; ret[m] = val%10+'0'; carry = val/10; } if ( carry>0 ) ret.insert(ret.begin(), carry+'0'); } return string(ret.begin(), ret.end()); } };