forked from leetcoders/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MultiplyStrings.h
36 lines (34 loc) · 1.06 KB
/
MultiplyStrings.h
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
/*
Author: Annie Kim, [email protected]
Date: Apr 23, 2013
Update: Aug 20, 2013
Problem: Multiply Strings
Difficulty: Easy
Source: http://leetcode.com/onlinejudge#question_43
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: Just like what we do when multiplying integers.
*/
class Solution {
public:
string multiply(string num1, string num2) {
int N = num1.size(), M = num2.size();
string res(N+M, '0');
for (int i = N - 1; i >= 0; --i)
{
int carry = 0;
for (int j = M - 1; j >= 0; --j)
{
int sum = carry + (res[i+j+1] - '0') +
(num1[i] - '0') * (num2[j] - '0');
res[i+j+1] = sum % 10 + '0';
carry = sum / 10;
}
res[i] += carry;
}
while (res.size() > 1 && res[0] == '0')
res.erase(res.begin());
return res;
}
};