Skip to content

Commit 85825d1

Browse files
committed
Solution to task 5
1 parent 273c8ce commit 85825d1

File tree

3 files changed

+99
-0
lines changed

3 files changed

+99
-0
lines changed

0x0C-more_malloc_free/101-mul

16.7 KB
Binary file not shown.

0x0C-more_malloc_free/101-mul.c

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
#include "main.h"
2+
#include <stdio.h>
3+
#include <stdlib.h>
4+
#include <string.h>
5+
6+
/**
7+
* isNumber - checks if a string is a number
8+
* @s: string to check
9+
* Return: 1 if number, 0 if not
10+
*/
11+
int isNumber(char *s)
12+
{
13+
int i;
14+
15+
for (i = 0; s[i]; i++)
16+
if (s[i] < '0' || s[i] > '9')
17+
return (0);
18+
return (1);
19+
}
20+
21+
/**
22+
* print_result - prints the result of the multiplication
23+
* @result: array of integers
24+
* @len: length of result
25+
* Return: void
26+
*/
27+
void print_result(int *result, int len)
28+
{
29+
int i;
30+
31+
for (i = 0; i < len && result[i] == 0; i++)
32+
;
33+
34+
if (i == len)
35+
printf("0");
36+
37+
for (; i < len; i++)
38+
printf("%d", result[i]);
39+
40+
printf("\n");
41+
}
42+
43+
/**
44+
* main - multiplies two positive numbers
45+
* @ac: number of arguments
46+
* @av: array of arguments
47+
* Return: 0
48+
*/
49+
int main(int ac, char **av)
50+
{
51+
int i, j, num1_len, num2_len;
52+
int *result;
53+
54+
if (ac != 3 || !isNumber(av[1]) || !isNumber(av[2]))
55+
{
56+
printf("Error\n");
57+
exit(98);
58+
}
59+
60+
num1_len = strlen(av[1]);
61+
num2_len = strlen(av[2]);
62+
63+
result = calloc(num1_len + num2_len, sizeof(int));
64+
if (result == NULL)
65+
{
66+
printf("Error\n");
67+
exit(98);
68+
}
69+
70+
for (i = num1_len - 1; i >= 0; i--)
71+
{
72+
for (j = num2_len - 1; j >= 0; j--)
73+
{
74+
int mul = (av[1][i] - '0') * (av[2][j] - '0');
75+
76+
int sum = result[i + j + 1] + mul;
77+
78+
result[i + j] += sum / 10;
79+
result[i + j + 1] = sum % 10;
80+
}
81+
}
82+
83+
print_result(result, num1_len + num2_len);
84+
free(result);
85+
return (0);
86+
}

0x0C-more_malloc_free/_putchar.c

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
#include <unistd.h>
2+
3+
/**
4+
* _putchar - writes the character c to stdout
5+
* @c: The character to print
6+
*
7+
* Return: On success 1.
8+
* On error, -1 is returned, and errno is set appropriately.
9+
*/
10+
int _putchar(char c)
11+
{
12+
return (write(1, &c, 1));
13+
}

0 commit comments

Comments
 (0)