LeetCode 43. Multiply Strings

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

Note:

  • 1.The length of both num1 and num2 is < 110.
  • 2.Both num1 and num2 contains only digits 0-9.
  • 3.Both num1 and num2 does not contain any leading zero.

You must not use any built-in BigInteger library or convert the inputs to integer directly.

典型的大整数乘法模拟

class Solution {

    void CharToInt(string &str, vector<short int> &arr)
    {
        for(int i=str.size()-1; i>=0; -- i)
            arr.push_back(str[i]-'0');
    }

    void sum(vector<short int> &res, vector<short int> &ans)
    {
        int add = 0;
        for(int i=0; i<res.size(); ++ i)
        {
            ans[i] = res[i] + ans[i] + add;
            add = ans[i] / 10;
            ans[i] %= 10;
        }
        int i = res.size();
        while(add != 0)
        {
            ans[i] = ans[i] + add;
            add = ans[i] / 10;
            ans[i] %= 10;
        }
    }

public:
    string multiply(string num1, string num2) {
        vector<short int> a, b;
        CharToInt(num1, a);
        CharToInt(num2, b);

        vector<short int> ans(12500, 0);
        for(int i=0; i<a.size(); ++ i)
        {
            vector<short int> res;
            for(int j=0; j<i; ++ j)
                res.push_back(0);
            int add = 0;
            for(int j=0; j<b.size(); ++ j)
            {
                int t = a[i] * b[j] + add;
                res.push_back(t % 10);
                add = t / 10;
            }
            if(add != 0)
                res.push_back(add);

            sum(res, ans);
        }

        string str;
        bool is = false;
        for(int i=12499; i>=0; -- i)
        {
            if(ans[i] != 0)
                is = true;

            if(is)
                str += ans[i] + '0';
        }
        if(is == false)
            return "0";
        return str;
    }
};
posted @ 2017-03-28 11:33  aiterator  阅读(157)  评论(0编辑  收藏  举报