43.字符串乘法

来源:互联网 发布:苹果6打不开数据流量 编辑:程序博客网 时间:2024/06/05 05:49

Multiply Strings

问题描述:

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.

测试代码:

   string result(num1.length()+num2.length(),'0');    int carry = 0,sum = 0;    string::iterator it;    for(int i=num1.length()-1;i>=0;i--)    {        carry = 0;        for(int j=num2.length()-1;j>=0;j--)        {            sum = (result[i+j+1]-'0'+(num1[i]-'0')*(num2[j]-'0')+carry)%10;            result[i+j+1] = sum%10+'0';            carry = sum/10;        }        result[i] += carry;    }    it = result.begin();    while(*it=='0')    {        result.erase(it);    }    if(result.empty())        return "0";    return  result;

性能:

这里写图片描述

参考答案:

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());   string out;   int carry=0;   string ret;   for(int i=0;i<num1.size();i++)   {        int pos=i;        for(int j=0;j<num2.size();j++)        {            int temp=(num1[i]-'0')*(num2[j]-'0')+carry;            if(pos<ret.length())            {                temp=ret[pos]-'0'+temp;                ret[pos]=temp%10+'0';            }            else{                ret.append(1,temp%10+'0');            }           carry=temp/10;           pos++;        }        if(carry>0)            ret.append(1,carry+'0');       carry=0;   }  reverse(ret.begin(),ret.end());   return ret;    }};

性能:

这里写图片描述