43. Multiply Strings (String)
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.
思路:首先确定结果的位数,难点在于知道结果中的每一位,是乘数中的哪两位相乘贡献的:是num2中的i-len1+1到i中的数分别乘以num1中的i-j相加而得的,并且要注意不能超过num2的界限[0,len2-1]
class Solution { public: string multiply(string num1, string num2) { reverse(num1.begin(), num1.end()); reverse(num2.begin(), num2.end()); int carry = 0, sum =0; string result=""; int len1 = num1.length(); int len2 = num2.length(); int resLen = len1+len2-1; for(int i = 0; i < resLen; i++){ //traverse the result digit for(int j = max(0,i-len1+1) ; j <= min(i,len2-1); j++){ //traverse the num2 digit sum += (num2[j]-'0')*(num1[i-j]-'0'); } sum += carry; carry = sum/10; result += ((sum%10) + '0'); sum=0;a } if(carry) result += (carry+'0'); reverse(result.begin(),result.end()); if(result[0]=='0') return "0"; //全0的情况 return result; } };