leetcode Multiply Strings

来源:互联网 发布:linux 查看进程日志 编辑:程序博客网 时间:2024/05/17 09:17

此题细节较多,需要格外小心

下面代码根据乘法的性质,对于num1 和num2, 从后往前用num1的每一位乘以num2,进行累加

需要注意的是累加过程中要记得左移且累加之前需要反转字符串


代码

class Solution {private:int shiftLeftNum;public:    string multiply(string num1, string num2) {                string res;        int len1 = num1.length();        int len2 = num2.length();shiftLeftNum = 1;                if(len1 == 0 || len2 == 0)            return res;                //处理其中一个数为0的情况        if(num1[0]=='0'||num2[0]=='0')            return res + '0';        //累加的过程          for(int i = len1-1; i >= 0; --i)        {            string tempBitRes = "";            int oneBit1 = num1[i] - '0';                        int carry = 0;            for(int j = len2-1; j >= 0; --j)            {                int oneBit2 = num2[j] - '0';                int multiNum = oneBit1*oneBit2 + carry;                carry = multiNum/10;                tempBitRes += ((multiNum%10)+'0');            }                        while(carry!=0)            {                                int multiNum = carry;                carry = multiNum/10;                tempBitRes += ((multiNum%10)+'0');                            }                        reverse(tempBitRes.begin(), tempBitRes.end());            AddOneBitMultiNum(res, tempBitRes);        }                return res;            }            void AddOneBitMultiNum(string &res, string tempBitRes)    {              int len1 = res.length();        int len2 = tempBitRes.length();                if(len1==0)        {            res = tempBitRes;            return ;        }        if(len2==0)            return ;            int shiftLef = shiftLeftNum;for(int i = 0; i < shiftLef; ++i)             tempBitRes += '0';    shiftLeftNum++;        string tempResult = "";        int carry = 0;             int i = len1-1;int j = len2 + shiftLef - 1;              while(i>=0&&j>=0)       {           int add = (res[i]-'0') + (tempBitRes[j]-'0') + carry;           carry = add/10;           tempResult += ((add%10) + '0');           --i;           --j;       }              while(i>=0)       {           int add = (res[i]-'0') + carry;           carry = add/10;           tempResult += ((add%10) + '0');           --i;       }                     while(j>=0)       {           int add = (tempBitRes[j]-'0') + carry;           carry = add/10;           tempResult += ((add%10) + '0');           --j;       }              while(carry!=0)       {           int add = carry;           carry = add/10;           tempResult += ((add%10) + '0');      }                            reverse(tempResult.begin(), tempResult.end());              res = tempResult;            }};

0 0