Monday, November 25, 2013

leetCode Problem : Multiply Strings

Problem


Given two numbers represented as strings, return multiplication of the numbers as a string.
Note: The numbers can be arbitrarily large and are non-negative.

Code

string multiply(string num1, string num2) {
    // IMPORTANT: Please reset any member data you declared, as
    // the same Solution instance will be reused for each test case.
    int n1 = num1.size();
    int n2 = num2.size();
    string A;
    A.resize(n1 + n2 + 1);
    for(int i = 0;i <= (n1+n2); ++i)
        A[i] = '0';    
    for(int i = n2 - 1;i >= 0; --i){
        int carry = 0;
        int carry_sum = 0;
        int j = n1 - 1;
        for(;j >= 0; --j){
            int prod = (num2[i] - '0')*(num1[j] - '0') + carry;
            int num = prod%10;carry = prod/10;
            int sum = num + (A[i + j + 2] - '0') + carry_sum;
            A[i + j + 2] = sum%10 +'0';carry_sum = sum/10;
        }
        int k = 0;
        carry = carry + carry_sum;
        while(carry != 0){
            A[i + j + 2 + k] = carry % 10 + '0';carry = carry /10;
            --k; 
        }
    }
    int pos = 0;
    while(A[pos] == '0')
        ++pos;
    if(pos == (n1+n2 + 1))
        return "0";
    string B;
    B.resize(n1 + n2 + 1 - pos);
    for(int i = pos;i < (n1+n2 + 1); ++i)
        B[i - pos] = A[i];
    return B;
}

No comments:

Post a Comment