|
| 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 | +} |
0 commit comments