-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathmultiply_strings.cpp
More file actions
46 lines (37 loc) · 1017 Bytes
/
multiply_strings.cpp
File metadata and controls
46 lines (37 loc) · 1017 Bytes
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
class Solution {
public:
string multiply(string num1, string num2) {
if (("0" == num1) || ("0" == num2)) {
return "0";
}
// 模仿竖式乘法
string result = "";
int i;
int j;
int flag = 0; // 进位标记
int steps = 0; // 移位数,用来表示十百千万...
for (i = num1.length() - 1; i >= 0; --i) {
int position = steps; // 结果数组当前的位置
for (j = num2.length() - 1; j >= 0; --j) {
int val = (num1[i] - '0') * (num2[j] - '0') + flag;
if (position < result.length()) {
val += result[position] - '0';
result[position] = (val % 10) + '0';
}
else {
result.append(1, (val % 10) + '0');
}
flag = val / 10;
++position;
}
// 单独处理最后一个进位
if (flag > 0) {
result.append(1, flag + '0');
}
flag = 0;
++steps;
}
reverse(result.begin(), result.end());
return result;
}
};