leetcode 43. Multiply Strings

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

Note:
The length of both num1 and num2 is < 110.
Both num1 and num2 contains only digits 0-9.
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.
题目大意:
求两个大数的乘积
思路:
模拟乘法,O(n^2)的解法...

class Solution {
public:
    string multiply(string num1, string num2) {
        int n = num1.size();
        int m = num2.size();
        vector<int>v(500);
        int k = 0;
        for (int i = n - 1; i >= 0; --i) {
            k = n - i - 1;
            for (int j = m - 1; j >= 0; --j) {
                v[k] += (num1[i] - '0') * (num2[j] - '0');
                if (v[k] >= 10) {
                    v[k+1] += v[k]/10;
                    v[k] %= 10;
                }
                ++k;
            }
        }
        string ans = "";
        int mark = 0;
        for (int i = 500 - 1; i >= 0; --i) {
            if (v[i] == 0 && mark == 0) continue;
            else {
                mark = 1;
                ans += v[i] + '0';
            }
        }
        if (ans == "") ans += '0';
        return ans;
    }
};
posted on 2017-10-10 22:56  Beserious  阅读(95)  评论(0编辑  收藏  举报