How to multiply two integers represented as strings and return the result also as a string in C++

2 Answers

0 votes
#include <iostream>
#include <string>
#include <vector>

std::string multiplyStrings(const std::string& num1, const std::string& num2) {
    if (num1 == "0" || num2 == "0") return "0";

    int n = num1.size(), m = num2.size();
    std::vector<int> result(n + m, 0);

    // Perform multiplication digit by digit
    for (int i = n - 1; i >= 0; --i) {
        for (int j = m - 1; j >= 0; --j) {
            int mul = (num1[i] - '0') * (num2[j] - '0');
            int sum = mul + result[i + j + 1];

            result[i + j + 1] = sum % 10;  // Store the unit place
            result[i + j] += sum / 10;    // Carry over to the next position
        }
    }

    // Convert result vector to string
    std::string product;
    for (int num : result) {
        if (!(product.empty() && num == 0)) {  // Skip leading zeros
            product.push_back(num + '0');
        }
    }

    return product.empty() ? "0" : product;
}

int main() {
    std::string num1 = "123";
    std::string num2 = "456";

    std::string result = multiplyStrings(num1, num2);
    std::cout << "Product: " << result << std::endl;
}


/*
run:

Product: 56088

*/

 



answered Jun 5, 2025 by avibootz
0 votes
#include <iostream>
#include <string>

std::string multiplyStrings(const std::string& num1, const std::string& num2) {
    // Convert strings to integers
    long long int n1 = std::stoll(num1);
    long long int n2 = std::stoll(num2);

    // Perform multiplication
    long long int result = n1 * n2;

    // Convert result back to string
    return std::to_string(result);
}

int main() {
    std::string num1 = "123";
    std::string num2 = "456";

    std::cout << "Result: " << multiplyStrings(num1, num2) << std::endl;
}



/*
run:

Result: 56088

*/

 



answered Jun 5, 2025 by avibootz
...