forked from lolosssss/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path43_multiply_strings.c
More file actions
53 lines (46 loc) · 1.13 KB
/
43_multiply_strings.c
File metadata and controls
53 lines (46 loc) · 1.13 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
/**
* Description : Multiply Strings
* Given two numbers represented as strings, return multipication
* of the numbers as a string
* Author : Evan Lau
* Date : 2016/05/15
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* multiply(char* num1, char* num2)
{
int len1 = strlen(num1);
int len2 = strlen(num2);
int carry = 0;
int tmp;
int i, j;
char *ret = (char *)malloc(sizeof(char) * (len1 + len2 + 2));
memset(ret, '0', len1 + len2);
ret[len1+len2] = '\0';
for (i = len1 - 1; i >= 0; i--)
{
carry = 0;
for (j = len2 - 1; j >= 0; j--)
{
tmp = (ret[i+j+1] - '0') + (num1[i] - '0') * (num2[j] - '0') + \
carry;
ret[i+j+1] = tmp % 10 + '0';
carry = tmp / 10;
}
ret[i] += carry;
}
for (i = 0; i < len1 + len2; i++)
{
if (ret[i] != '0')
return ret + i;
}
return "0";
}
int main(void)
{
char num1[] = "12";
char num2[] = "23";
printf("%s * %s = %s\n", num1, num2, multiply(num1, num2));
return 0;
}