您的位置:首页 > 其它

LeetCode 43. Multiply Strings(字符串乘法)

2018-03-20 14:06 459 查看
题目描述:
Given two non-negative integers 
num1
 and 
num2
 represented as strings, return the product of 
num1
 and 
num2
.
Note:
    1. The length of both 
num1
 and 
num2
 is < 110.
    2. Both 
num1
 and 
num2
 contains only digits 
0-9
.
    3. Both 
num1
 and 
num2
 does not contain any leading zero.
    4. You must not use any built-in BigInteger library or convert the inputs to integer directly.
分析:
    题意:给定两个字符串表示的非负整型数num1、num2(长度均小于110,只包含数字0-9,不包含前置0),返回它们对应的乘积字符串。
    思路:这是一道经典的字符串乘法问题,我们按照多位数乘法规则、模拟整个过程即可。假设两个字符串的长度分别为n1、n2,需要注意几个点:① 它们的乘积字符串长度不会超过(n1 + n2);② 首先对被乘数、乘数进行反转、方便乘法运算操作;③ 每次被乘数都从首位开始计算、乘法从下一位(继上一次操作之后)开始计算;④ 最后对保存乘积的字符串进行前置0、反转处理。
    时间复杂度为O(n1 * n2)。

代码:
#include <bits/stdc++.h>

using namespace std;

class Solution {
public:
string multiply(string num1, string num2) {
int n1 = num1.length(), n2 = num2.length();
// Exceptional Case:
if(n1 == 0 || n2 == 0){
return "0";
}
if((n1 == 1 && num1[0] == '0') || (n2 == 1 && num2[0] == '0')){
return "0";
}
// reverse
reverse(num1.begin(), num1.end());
reverse(num2.begin(), num2.end());
// answer
string ans;
ans.assign(n1 + n2 + 1, '0');
for(int i = 0; i <= n2 - 1; i++){
int carry = 0, num = 0;
int s = i;
for(int j = 0; j <= n1 - 1; j++){
int temp = (num2[i] - '0') * (num1[j] - '0') + carry + (ans[s] - '0');
carry = temp / 10;
num = temp % 10;
ans[s++] = num + '0';
}
if(carry){
ans[s++] = carry + '0';
}
}
// get answer
int pos = -1;
for(int i = n1 + n2; i >= 0; i--){
if(ans[i] != '0'){
pos = i;
break;
}
}
ans = ans.substr(0, pos + 1);
reverse(ans.begin(), ans.end());
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C LeetCode String Math