-
Notifications
You must be signed in to change notification settings - Fork 0
/
101-mul.c
92 lines (87 loc) · 1.61 KB
/
101-mul.c
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
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
/**
* _isnumber - checks if string is number
*
* @s: string
*
* Return: 1 if number, 0 if not
*/
int _isnumber(char *s)
{
int i, check, d;
d = 0, check = 1;
for (i = 0; *(s + i) != 0; i++)
{
d = isdigit(*(s + i));
if (d == 0)
{
check = 0;
break;
}
}
return (check);
}
/**
* _callocX - reserves memory initialized to 0
*
* @nmemb: # of bytes
*
* Return: pointer
*/
char *_callocX(unsigned int nmemb)
{
unsigned int i;
char *p;
p = malloc(nmemb + 1);
if (p == 0)
return (0);
for (i = 0; i < nmemb; i++)
p[i] = '0';
p[i] = '\0';
return (p);
}
/**
* main - multiplies inf numbers
*
* @argc: # of cmd line args
* @argv: cmd line args
* Return: No return
*/
int main(int argc, char **argv)
{
int i, j, l1, l2, lful, mul, add, ten, ten2, tl, zer = 0;
char *res;
if (argc != 3 || _isnumber(argv[1]) == 0 || _isnumber(argv[2]) == 0)
printf("Error\n"), exit(98);
if (atoi(argv[1]) == 0 || atoi(argv[2]) == 0)
printf("0\n"), exit(0);
l1 = strlen(argv[1]), l2 = strlen(argv[2]);
lful = l1 + l2;
res = _callocX(lful);
if (res == 0)
printf("Error\n"), exit(98);
for (i = l2 - 1; i >= 0; i--)
{
ten = 0, ten2 = 0;
for (j = l1 - 1; j >= 0; j--)
{
tl = i + j + 1;
mul = (argv[1][j] - '0') * (argv[2][i] - '0') + ten;
ten = mul / 10;
add = (res[tl] - '0') + (mul % 10) + ten2;
ten2 = add / 10;
res[tl] = (add % 10) + '0';
}
res[tl - 1] = (ten + ten2) + '0';
}
if (res[0] == '0')
zer = 1;
for (; zer < lful; zer++)
printf("%c", res[zer]);
printf("\n");
free(res);
return (0);
}