[leetcode] 43. Multiply Strings(大数相乘)

来源:互联网 发布:ubuntu 打字 编辑:程序博客网 时间:2024/06/05 17:44

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 num2contains only digits 0-9.
3. Both num1 and num2 does not contain any leading zero.
4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

我的代码

大数相乘:看代码中注意点

class Solution {public:    string multiply(string num1, string num2) {        int len1 = num1.length();        int len2 = num2.length();        if (len1 == 0 || len2 == 0)  return "0";        int *rlt = new int[(len1 + len2)];  //乘积的位数为len1+len2或者len1+len2-1        memset(rlt, 0, (len1 + len2)*sizeof(int));        for (int i = 0; i < len1; i++)        {            for (int j = 0; j < len2; j++)            {                rlt[i + j + 1] += (num1[i] - '0')*(num2[j] - '0');                //之所以加个1是为了把首位空出来放进位            }        }        for (int i = len1+len2-1; i >=1; i--)        {            if (rlt[i] >= 10) //进位            {                rlt[i - 1] += (rlt[i] / 10);                rlt[i] = rlt[i] % 10;            }        }        int ind = 0;        while ((rlt[ind] == 0) && ind < len1+len2-1) ind++; //去掉开头的0,要考虑结果为0的情况,不能输出如“0000”而要输出“0”        string sRlt="";        for (; ind < len1 + len2; ind++)        {            sRlt += (rlt[ind] + '0');        }        delete[] rlt;        return sRlt;    }};