Interview Question Series | Season 2

Problem Explanation:

Given two non-negative integers represented as strings (num1 and num2), we are tasked with calculating the product of these two numbers without converting them directly to integers (no built-in BigInteger library). We need to simulate the multiplication of two large numbers, just like how it’s done manually on paper.

The general approach is similar to multiplying numbers manually:

  1. Multiply each digit of the first number with each digit of the second number.
  2. Keep track of the positions where these products should be placed.
  3. Handle carries properly.
  4. Build the final result string.

Approach:

  1. Reverse the digits: We’ll iterate from the least significant digits (rightmost) of both numbers to simulate manual multiplication.
  2. Temporary result array: Use an array to store intermediate results, where the index represents the place value.
  3. Digit multiplication: Multiply each digit of num1 with each digit of num2 and store the results in the appropriate positions in the temporary array.
  4. Carry handling: Once the multiplication is complete, handle carries by processing the tempResult array.
  5. Convert to string: Convert the result from the tempResult array to a string and handle leading zeros.

Code:

#include <stdio.h>
#include <string.h>

#define MAX_LEN 1000

// Function to multiply two strings num1 and num2, and store the result in result
void multiplyStrings(const char* num1, const char* num2, char* result) {
    int len1 = strlen(num1);
    int len2 = strlen(num2);

    // Create a temporary array to store the intermediate results
    int tempResult[MAX_LEN] = {0};

    // Multiply each digit from num1 and num2
    for (int j = len2 - 1; j >= 0; --j) {
        for (int i = len1 - 1; i >= 0; --i) {
            int digit1 = num1[i] - '0';
            int digit2 = num2[j] - '0';
            int mul = digit1 * digit2;

            // The position in the result array
            int p1 = i + j;
            int p2 = i + j + 1;

            // Add the multiplication result to the tempResult at p2
            int sum = mul + tempResult[p2];
            tempResult[p2] = sum % 10;       // Store the current digit
            tempResult[p1] += sum / 10;      // Carry to the next position
        }
    }

    // Convert the result to a string, ignoring leading zeros
    int index = 0;
    while (index < len1 + len2 && tempResult[index] == 0) {
        ++index;
    }

    // If there are no non-zero digits, the result is "0"
    if (index == len1 + len2) {
        result[0] = '0';
        result[1] = '';
        return;
    }

    // Construct the result string
    int k = 0;
    while (index < len1 + len2) {
        result[k++] = tempResult[index++] + '0';
    }
    result[k] = '';  // Null terminate the result string
}

int main() {
    char num1[MAX_LEN] = "123";       // First number as string
    char num2[MAX_LEN] = "456";       // Second number as string
    char result[MAX_LEN * 2] = {0};   // Result string

    multiplyStrings(num1, num2, result);  // Call the function to multiply

    printf("Product: %sn", result);   // Print the result

    return 0;
}

Explanation of the Code:

  1. multiplyStrings function:

    • The tempResult array is used to store intermediate results of the multiplication.
    • We iterate through the digits of num1 and num2 in reverse order (from least significant digit to the most significant).
    • Each product of two digits is stored in the tempResult array at the correct position. The position is determined by the sum of the indices of the digits being multiplied (i + j and i + j + 1 for the carry).
    • We then handle any carries by adding them to the corresponding position in tempResult.
  2. Building the result string:

    • We skip over any leading zeros in the tempResult array.
    • We then convert the result from tempResult into a string and store it in result.
  3. Final check:

    • If the result contains only zeros, we return "0".
  4. Printing the result: Finally, the main function prints the product.


Example:

  1. Input:
    num1 = "123", num2 = "456"

    Process:

    • Multiply each digit of 123 with 456 manually, storing the intermediate results.
    • The intermediate array (tempResult) will be updated as follows:
      tempResult = {0, 0, 5, 5, 6, 0, 8, 8}
      
    • The result is then built as "56088".

    Output:
    "56088"

  2. Input:
    num1 = "2", num2 = "3"

    Output:
    "6"


Time and Space Complexity:

  • Time Complexity:

    • The time complexity is O(n * m), where n is the length of num1 and m is the length of num2. This is because we perform a nested loop where each digit of num1 is multiplied by each digit of num2.
  • Space Complexity:

    • The space complexity is O(n + m), where n and m are the lengths of num1 and num2, respectively. This is the space required for the tempResult array and the result string.

This approach efficiently solves the problem using basic string manipulation and simulates the manual multiplication process without using any built-in BigInteger library.

Scroll to Top