-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmultiply_strings.cpp
More file actions
105 lines (94 loc) · 2.56 KB
/
multiply_strings.cpp
File metadata and controls
105 lines (94 loc) · 2.56 KB
1
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
* =====================================================================================
*
* Filename: multiply_strings.cpp
*
* Description: Multiply Strings.
* Given two non-negative integers num1 and num2 represented as strings,
* return the product of num1 and num2, also represented as a string.
*
* Version: 1.0
* Created: 02/15/19 03:40:15
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <string>
#include <vector>
class Solution
{
public:
std::string multiply(const std::string& num1, const std::string& num2)
{
std::vector<int> values;
values.reserve(num1.size() + num2.size());
int idx1 = 0;
auto iter1 = num1.rbegin();
while (iter1 != num1.rend())
{
int idx2 = 0;
auto iter2 = num2.rbegin();
while (iter2 != num2.rend())
{
int i = idx1 + idx2;
if (values.size() < (i + 1))
{
values.resize(i + 1);
}
values[i] += (*iter1 - '0') * (*iter2 - '0');
while (values[i] >= 10)
{
if (values.size() < (i + 2))
{
values.resize(i + 2);
}
int prefix = values[i] / 10;
values[i] = values[i] % 10;
values[i + 1] += prefix;
i++;
}
iter2++;
idx2++;
}
iter1++;
idx1++;
}
std::string str;
bool is_zero = true;
auto iter = values.rbegin();
while (iter != values.rend())
{
if (is_zero && (*iter == 0))
{
iter++;
continue;
}
is_zero = false;
str.push_back((char)(*iter + '0'));
iter++;
}
if (str.empty())
{
str = "0";
}
return str;
}
};
int main(int argc, char* argv[])
{
std::string num1 = "123";
std::string num2 = "456";
if (argc >= 3)
{
num1 = argv[1];
num2 = argv[2];
}
auto num = Solution().multiply(num1, num2);
printf("%s * %s = %s\n", num1.c_str(), num2.c_str(), num.c_str());
return 0;
}