forked from rost0413/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultiply_Strings.cpp
More file actions
79 lines (73 loc) · 1.67 KB
/
Multiply_Strings.cpp
File metadata and controls
79 lines (73 loc) · 1.67 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
/*
Author: Weixian Zhou, ideazwx@gmail.com
Date: Jul 8, 2012
Problem: Multiply Strings
Difficulty: easy
Source: http://www.leetcode.com/onlinejudge
Notes:
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.
Solution:
*/
#include <vector>
#include <set>
#include <climits>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <cmath>
#include <cstring>
using namespace std;
class Solution {
public:
string reverse(string str) {
string r;
for (int i = str.length() - 1; i >= 0; i--) {
r += str[i];
}
return r;
}
string add(string num1, string num2) {
stringstream result;
unsigned carry, i;
for (i = 0, carry = 0; i < num1.length() && i < num2.length(); i++) {
int sum = num1[i] - '0' + num2[i] - '0' + carry;
result << sum % 10;
carry = sum / 10;
}
num1 = (i < num1.length() ? num1 : num2);
for (; i < num1.length(); i++) {
int sum = num1[i] - '0' + carry;
result << sum % 10;
carry = sum / 10;
}
if (carry) {
result << carry;
}
return result.str();
}
string multiply(string num1, string num2) {
string result;
string cum[10];
num1 = reverse(num1);
num2 = reverse(num2);
cum[0] = "0";
for (unsigned i = 1; i <= 9; i++) {
cum[i] = add(cum[i - 1], num1);
}
for (unsigned i = 0; i < num2.length(); i++) {
string factor;
for (unsigned j = 0; j < i; j++) {
factor += "0";
}
if (cum[(int) (num2[i] - '0')].compare("0") == 0) {
factor = "0";
} else {
factor += cum[(int) (num2[i] - '0')];
}
result = add(result, factor);
}
return reverse(result);
}
};