# LeetCode:Multiply Strings

368人阅读 评论(0)

### 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

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;

}
};

个人资料
等级：
访问量： 39万+
积分： 6853
排名： 4152
博客专栏
 Java源码解析 文章：12篇 阅读：13330 LeetCode解题记录 文章：216篇 阅读：277639 FFmpeg4Android 文章：7篇 阅读：1030
最新评论
友情链接