leetcode43. Multiply Strings

来源:互联网 发布:生产线电子看板数据 编辑:程序博客网 时间:2024/06/08 04:05
class Solution {public:    string multiply(string num1, string num2) {        if(num1.size()<=0 || num2.size()<=0) return "0";        int maxPos =  num2.size() - 1;        string product="0";        string tempProduct = "";        int zerosLen = 0;        for(int i = maxPos ; i>=0 ; i--){            zerosLen = maxPos - i;            tempProduct = multiplyChar(num1,num2[i]);            if(tempProduct!="0"){                    tempProduct += string(zerosLen,'0');                    product = add(product,tempProduct);             }        }        return product;    }    string multiplyChar(string num1,char num2){        if(num1.size()<=0 || num2 == '0' || num1=="0") return "0";        int tempInt  =num2 - '0';        string temp ="";        int carry = 0;        for(int i = num1.size() - 1;i>=0;i--){            temp = string(1,(((num1[i] - '0') * tempInt  + carry)% 10) +'0') + temp;            carry = ((num1[i] - '0') * tempInt  + carry) / 10 ;        }        if(carry>0) temp = string(1,carry+'0')+temp;        return temp;    }    string add(string num1, string num2){        if(num1.size()<=0 || num2.size()<=0) return num1+num2;         if(num1 == "0") return num2;        if(num2 == "0") return num1;        int cursor1 = num1.size() - 1;        int cursor2 = num2.size() - 1;        int carry = 0;        string temp="";        while(cursor1>=0 || cursor2>=0){            int toAdd1 = cursor1>=0 ? num1[cursor1] - '0' : 0;            int toAdd2 = cursor2>=0 ? num2[cursor2] - '0' : 0;            temp = string(1,(( toAdd1+ toAdd2  + carry) % 10) +'0') + temp;            carry = ( toAdd1+ toAdd2  + carry) / 10;            cursor1>=0 && (cursor1--);            cursor2>=0 && (cursor2--);        }        if(carry>0) temp = '1'+temp;        return temp;    }};
原创粉丝点击