ronith
8/17/2018 - 6:43 AM

Multiply Large Numbers represented as Strings

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

string add (string s, string k) {
    int num, carry = 0;
    string res;

    int i=s.length()-1, j = k.length()-1;
    if (i<j)
        return add(k,s);
    while (i>=0 && j>=0) {
        num= carry + (s[i]-'0')+ (k[j]- '0');
        carry = num/10;
        res.push_back(num%10+ '0');
        if (i==0 && num/10>0)
            res.push_back(num/10+ '0');
        i--;
        j--;
    }
    while (i>=0) {
        num= carry + (s[i]-'0');
        carry = num/10;
        res.push_back(num%10+ '0');
        if (i==0 && num/10>0)
            res.push_back(num/10+ '0');
        i--;
    }
    reverse(res.begin(), res.end());
    return res;

}

string multiply (string s, char k) {
    int num, carry = 0;
    string res;
    for (int i=s.length()-1; i>=0;i--) {
        num = carry + (s[i]-'0')*(k- '0');
        carry = num/10;
        res.push_back(num%10+ '0');
        if (i==0 && num/10>0)
            res.push_back(num/10 + '0');
    }
    reverse(res.begin(), res.end());
    return res;
}

void func (string num1, string num2) {
    int n1 = num1.length()-1, n2 = num2.length()-1;
    string sum= "0";
    for (int i=n2;i>=0;i--) {
        string res = multiply (num1, num2[i]);
        int j=n2-i;
        while (j-->0)
            res+= '0';
        sum = add(sum, res);
    }
    cout<< sum;
    return;
}

int main() {
    string num, div;
    string num1, num2;
    getline(cin, num1);
    getline(cin, num2);
    func(num1, num2);
    return 0;
}