43. Multiply Strings
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.
Example 1:
Input: num1 = “2”, num2 = “3”
Output: “6”
Example 2:
Input: num1 = “123”, num2 = “456”
Output: “56088”
Constraints:
- 1 <= num1.length, num2.length <= 200
- num1 and num2 consist of digits only.
- Both num1 and num2 do not contain any leading zero, except the number 0 itself.
From: LeetCode
Link: 43. Multiply Strings
Solution:
Ideas:
- It first checks if either input string is “0”. If so, the result is “0”.
- It calculates the lengths of the input strings and allocates an array to store the intermediate product results.
- It iterates through each digit of the two numbers, multiplies the digits, and adds them to the appropriate position in the result array, taking care of positional value by using array indices.
- It then converts the array into a string, adjusting for carries in the digits.
- Finally, it formats the result into a string, handling leading zeros if necessary.
Code:
char* multiply(char* num1, char* num2) {
// If one of the numbers is "0", the result is "0"
if (strcmp(num1, "0") == 0 || strcmp(num2, "0") == 0) {
char* result = malloc(2);
strcpy(result, "0");
return result;
}
int len1 = strlen(num1);
int len2 = strlen(num2);
int lenResult = len1 + len2;
// Array to store result of multiplication
int *result = calloc(lenResult, sizeof(int));
// Multiply each digit from num1 by each digit from num2 and store in result
for (int i = len1 - 1; i >= 0; i--) {
for (int j = len2 - 1; j >= 0; j--) {
int index = (len1 - 1 - i) + (len2 - 1 - j);
int mul = (num1[i] - '0') * (num2[j] - '0');
result[index] += mul;
}
}
// Handle carry and convert int array to string
for (int i = 0; i < lenResult - 1; i++) {
result[i + 1] += result[i] / 10;
result[i] %= 10;
}
// Remove leading zeros and prepare final string
int start = lenResult - 1;
while (start >= 0 && result[start] == 0) {
start--;
}
char* finalResult = malloc(start + 2); // +1 for null terminator
for (int i = start; i >= 0; i--) {
finalResult[start - i] = result[i] + '0';
}
finalResult[start + 1] = '\0';
// Free the temporary result array
free(result);
return finalResult;
}