leetcode---Multiply Strings---大整数乘法

来源:互联网 发布:sqlserver格式化工具 编辑:程序博客网 时间:2024/05/19 23:03

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;    }};
0 0
原创粉丝点击