Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Exercises: Calculate the product of two positive integers represented as strings

C++ Math: Exercise-20 with Solution

Write a C++ program to calculate the product of two positive integers represented as strings. Return the result as a string.

Sample Input: sn1 = "12"
sn2 = "5"
Sample Output: 12 X 5 = 60

Sample Input: sn1 = "48"
sn2 = "85"
Sample Output: 48 X 85 = 4080

Sample Solution:

C++ Code :

#include <iostream>
#include <algorithm>
#include <vector> 
#include <functional>

using namespace std; 
  
string multiply(string sn1, string sn2) {
        const auto char_to_int = [](const char c) { return c - '0'; };
        const auto int_to_char = [](const int i) { return i + '0'; };

        vector<int> n1;
        transform(sn1.rbegin(), sn1.rend(), back_inserter(n1), char_to_int);
        vector<int> n2;
        transform(sn2.rbegin(), sn2.rend(), back_inserter(n2), char_to_int);

        vector<int> temp(n1.size() + n2.size());
        for(int i = 0; i < n1.size(); ++i) {
            for(int j = 0; j < n2.size(); ++j) {
                temp[i + j] += n1[i] * n2[j];
                temp[i + j + 1] += temp[i + j] / 10;
                temp[i + j] %= 10;
            }
        }
            
        string result;
        transform(find_if(temp.rbegin(), prev(temp.rend()),
                         [](const int i) { return i != 0; }),
                  temp.rend(), back_inserter(result), int_to_char);
        return result;
    }
  
int main()  
{  
    string sn1 = "12";
    string sn2 = "5";    
	cout << sn1 <<" X " << sn2 << " = " << multiply(sn1, sn2) << endl;
    sn1 = "48";
    sn2 = "85";    
	cout << sn1 <<" X " << sn2 << " = " << multiply(sn1, sn2) << endl;	    
    return 0;  
}  

Sample Output:

12 X 5 = 60
48 X 85 = 4080

Flowchart:

Flowchart: Calculate the product of two positive integers represented as strings

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to convert a given roman numeral to a integer.

Next: Write a C++ program to check if a given string is a decimal number or not.

What is the difficulty level of this exercise?