leetcode---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.
Converting the input string to integer is NOT allowed.
You should NOT use internal library such as BigInteger.

class Solution {
public:
    string multiply(string num1, string num2) 
    {
         reverse(num1.begin(), num1.end());
         reverse(num2.begin(), num2.end());
         int l1 = num1.size();
         int l2 = num2.size();
         int ans[l1+l2];
         memset(ans, 0, sizeof(ans));
         for(int i=0; i<l1; i++)
            for(int j=0; j<l2; j++)
                ans[i+j] += (num1[i] - '0') * (num2[j] - '0');

        int c = 0;
        int i = 0;
        while(i < l1 + l2 - 1 || c)
        {
            int s = ans[i] + c;
            ans[i] = s % 10;
            c = s / 10;
            i++;
        }
        string result = "";
        i = l1 + l2 - 1;
        while(i && ans[i] == 0) //去掉前面的0
            i--;
        if(i == 0 && ans[i] == 0)
            return "0";
        while(i >= 0)
        {
            result = result + (char)(ans[i] + '0');
            i--;
        }
        return result;
    }
};
    原文作者:大整数乘法问题
    原文地址: https://blog.csdn.net/u012319493/article/details/51510931
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞