Leetcode之Multiply Strings
来源:互联网 发布:塞班宝软网java 编辑:程序博客网 时间:2024/06/11 14:48
字符串相乘,题目如下:
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.
根据上面的字符串的相乘,变成数组相乘。
C++ Code
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Solution
{
public:
string multiply(string s1, string s2)
{
if(s1 == "0" || s2 == "0") return "0";
int len1 = s1.length();
int len2 = s2.length();
int len3 = len1 + len2;
vector<int> num1(len1, 0);
vector<int> num2(len2, 0);
vector<int> num3(len1 + len2, 0);
for(int i = 0; i < len1; i++)
{
num1[i] = s1[i] - '0';
}
for(int i = 0; i < len2; i++)
{
num2[i] = s2[i] - '0';
}
for(int i = 0; i < len1; i++)
{
for(int j = 0; j < len2; j++)
{
num3[i + j + 1] += num1[i] * num2[j];
}
}
string ss = "";
for(int i = len3 - 1; i >= 0; i--)
{
if(i > 0)
{
num3[i - 1] += num3[i] / 10;
}
num3[i] = num3[i] % 10;
ss = char(num3[i] + '0') + ss;
}
ss = ss[0] == '0' ? ss.substr(1) : ss;
return ss;
}
};
{
public:
string multiply(string s1, string s2)
{
if(s1 == "0" || s2 == "0") return "0";
int len1 = s1.length();
int len2 = s2.length();
int len3 = len1 + len2;
vector<int> num1(len1, 0);
vector<int> num2(len2, 0);
vector<int> num3(len1 + len2, 0);
for(int i = 0; i < len1; i++)
{
num1[i] = s1[i] - '0';
}
for(int i = 0; i < len2; i++)
{
num2[i] = s2[i] - '0';
}
for(int i = 0; i < len1; i++)
{
for(int j = 0; j < len2; j++)
{
num3[i + j + 1] += num1[i] * num2[j];
}
}
string ss = "";
for(int i = len3 - 1; i >= 0; i--)
{
if(i > 0)
{
num3[i - 1] += num3[i] / 10;
}
num3[i] = num3[i] % 10;
ss = char(num3[i] + '0') + ss;
}
ss = ss[0] == '0' ? ss.substr(1) : ss;
return ss;
}
};
0 0
- Leetcode之Multiply Strings
- LeetCode之Multiply Strings
- 【Leetcode】之Multiply Strings
- LeetCode 之 Multiply Strings
- LeetCode算法题之Multiply Strings
- Leetcode学习之Multiply Strings (43)
- LeetCode 43题之 Multiply Strings
- LeetCode进阶之路( Multiply Strings)
- LeetCode: Multiply Strings
- LeetCode Multiply Strings
- LeetCode: Multiply Strings
- [Leetcode] Multiply Strings
- [LeetCode] Multiply Strings
- [Leetcode] Multiply Strings
- LeetCode 45: Multiply Strings
- [LeetCode]Multiply Strings
- [LeetCode] Multiply Strings
- LeetCode-Multiply Strings
- 整理大型网站架构必知必会的几个服务器知识
- ubuntu---apt-cache命令的用法
- 致胡须
- 求1+2+…+n
- 在服务器端判断request来自Ajax请求(异步)还是传统请求(同步)
- Leetcode之Multiply Strings
- MMORGP大型游戏设计与开发(客户端架构 part16 of vegine)
- itext报错PdfReader not opened with owner password
- 系统构架设计应考虑的因素
- 文件最近替换算法
- 国大药房-移动支付仅仅是一个开始
- Context.getDir
- android 设置默认launcher 附上代码
- 文件替换