标签:
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.
思路:
3 4
* 1 3
——————
9 12
3 4
——————
3 13 12
再处理进位:
3 13 12 - > 3 14 2 -> 4 4 2
class Solution { public: string multiply(string num1, string num2) { reverse(num1.begin(), num1.end()); reverse(num2.begin(), num2.end()); int carry = 0; string result; int len1 = num1.length(); int len2 = num2.length(); int resLen = len1+len2-1; for(int resPos = 0; resPos<resLen;++resPos) //indicate the pos of the result { int sum = 0; for(int i = max(0,resPos-len2+1); i < len1; ++i) //traverse the digit of num1 { int j = resPos-i; //indicate the pos of num2 if(j < 0) break; sum += (num1[i]-‘0‘)*(num2[j]-‘0‘); } sum += carry; result.push_back(sum % 10+‘0‘); carry = sum/10; } while(carry > 0) { result.push_back(carry % 10+‘0‘); carry /= 10; } reverse(result.begin(), result.end()); if(result.find_first_not_of(‘0‘) == string::npos) return "0";//排除全0的情况 else return result; } };
标签:
原文地址:http://www.cnblogs.com/qionglouyuyu/p/4930350.html