您的位置:首页 > 其它

LeetCode:Multiply Strings

2016-05-30 11:49 387 查看


Multiply Strings

Total Accepted: 62981 Total
Submissions: 265241 Difficulty: Medium

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.

Subscribe to see which companies asked this question

Hide Tags
Math String

Hide Similar Problems
(M) Add Two Numbers (E)
Plus One (E) Add Binary

思路:

如:num1="123",num2="45";对应结果存储在ans[num1.size()+num2.size()]中。

从右到左对位相乘,只要确定相乘后的结果在ans中位置即可。

参考讨论区的图:



即:num1[i] * num2[j]相乘后的对应位置为:i+j和i+j+1。

c++ code:

class Solution {
public:
string multiply(string num1, string num2) {

int len1 = num1.size(),len2 = num2.size();

string ans(len1+len2,'0');

for(int i=len1-1;i>=0;i--) {
for(int j=len2-1;j>=0;j--) {

int mul = (num1[i]-'0') * (num2[j]-'0');
int p1 = i + j;
int p2 = p1 + 1;
int sum = mul + ans[p2]-'0';
ans[p2] = sum % 10 + '0';
ans[p1] += sum / 10; // 这里ans[p1]-'0',而sum/10+'0',因此抵消
}
}

// 去掉前面的0
int start  = 0;
while(ans[start]=='0') start++;
ans = ans.substr(start);

return ans.size()==0 ? "0" : ans;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: