leetcode 43. Multiply Strings(高精度乘法)

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.
  • Converting the input string to integer is NOT allowed.
  • You should NOT use internal library such as BigInteger.

高精度乘法。需要注意的是char表示的数字和int对应的数字之间的转化。

class Solution {
public:
string multiply(string num1, string num2) {
int l1=num1.length(),l2=num2.length();
if(l1==||l2==){
string ans="";
return ans;
}
string ans(l1+l2,'');
for(int i=l1-;i>=;i--){
int add=;
for(int j=l2-;j>=;j--){
int t=(ans[i+j+]-'')+(num1[i]-'')*(num2[j]-'')+add;
ans[i+j+]=t%+'';
add=t/;
}
ans[i]=add+'';
}
size_t s0 = ans.find_first_not_of('');
if(s0!=string::npos){
return ans.substr(s0);
}
return "";
}
};
上一篇:[LeetCode] 43. Multiply Strings 字符串相乘


下一篇:【一天一道LeetCode】#43. Multiply Strings