【LeetCode】43. Multiply Strings

Multiply Strings

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.

 

将乘积逐位逆序存放在int数组result中。

记num1当前为第i位,num2当前为第j位,则乘积存放在result[(n1-1-i)+(n2-1-j)]中。

注意进位,当num1[i]与num2的每一位都相乘之后,如果仍有进位,需要存放在result[(n1-1-i)+n2]中。

最后将result逆序,去掉前面的0.但是如果全为0就返回"0"。

class Solution {
public:
    string multiply(string num1, string num2) {
        int n1 = num1.size();
        int n2 = num2.size();
        vector<int> result(n1+n2);
        string resultStr;
        
        for(int i = n1-1; i >= 0; i --)
        {// for num1[i]
            int carry = 0;
            int val1 = num1[i] - '0';
            for(int j = n2-1; j >= 0; j --)
            {// for num2[j]
                int val2 = num2[j] - '0';
                int res = val1 * val2;
                int ind = (n1-1-i)+(n2-1-j);
                result[ind] += carry;
                result[ind] += res;

                carry = result[ind] / 10;
                result[ind] %= 10;
            }
            if(carry != 0)
            {
                int ind = (n1-1-i)+n2;
                result[ind] += carry;
            }
        }
        //reverse result
        reverse(result.begin(), result.end());
        int i;
        for(i = 0; i < n1+n2; i ++)
        {
            if(result[i] != 0)
                break;
        }
        if(i == n1+n2)
        //all 0
            return "0";
        else
        {
            for(; i < n1+n2; i ++)
            {
                resultStr += (result[i] + '0');
            }
            return resultStr;
        }
    }
};

posted @ 2014-12-13 22:51  陆草纯  阅读(206)  评论(0编辑  收藏  举报