LeetCode--Multiply Strings

来源:互联网 发布:轻松抠图软件 编辑:程序博客网 时间:2024/06/16 03:29

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

Note:
The length of both num1 and num2 is < 110.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
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) {        if(num1.empty()||num2.empty())            return "";        if(num1=="0"||num2=="0")            return "0";        reverse(num1.begin(),num1.end());        reverse(num2.begin(),num2.end());        int len1=num1.size(),len2=num2.size();        string ret="";        int carry=0;        for(int i=0;i<len1;i++){            int pos=i;            for(int j=0;j<len2;j++){                int temp=(num1[i]-'0')*(num2[j]-'0')+carry;                if(pos<ret.length()){                    temp+=ret[pos]-'0';                    ret[pos]=temp%10+'0';                }                else                    ret+=temp%10+'0';                carry=temp/10;                pos++;            }            if(carry)                ret+=carry+'0';            carry=0;        }        reverse(ret.begin(),ret.end());        return ret;    }};
原创粉丝点击