加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Leetcode: Multiply Strings

发布时间:2020-12-14 03:57:10 所属栏目:大数据 来源:网络整理
导读:Given two numbers represented as strings,return multiplication of the numbers as a string. Note: The numbers can be arbitrarily large and are non-negative. 方法一:模拟手算乘法 string addTwoString(string num1,string num2){int len1 = num1.s

Given two numbers represented as strings,return multiplication of the numbers as a string.

Note: The numbers can be arbitrarily large and are non-negative.

方法一:模拟手算乘法

string addTwoString(string num1,string num2)
	{
		int len1 = num1.size()-1;
		int len2 = num2.size()-1;
		bool carry = false;
		string res = "";
		while(len1 >=0 && len2 >=0)
		{
			int a = num1[len1]-'0';
			int b = num2[len2]-'0';
			int c = a+b;
			if(carry)
			{
				c+=1;
				carry=false;
			}
			if(c>9)
			{
				carry=true;
				c -= 10;
			}
			char tmp = '0'+c;
			res = tmp + res;
			len1--;
			len2--;
		}
		string pre="";
		if(len1>=0)
			pre=num1.substr(0,len1+1);
		else if(len2>=0)
			pre=num2.substr(0,len2+1);
		if(carry){
			int sz=pre.size()-1;
			while(sz>=0 && pre[sz]=='9')
			{
				pre[sz]='0';
				sz--;
			}
			if(sz<0)
				pre='1'+pre;
			else
				pre[sz]+=1;
		}
		res = pre+res;
		return res;
	}
	string multiplyOneBit(string num1,int num2)
	{
		int len = num1.size();
		int* res = new int[len+1];
		memset(res,sizeof(int)*(len+1));
		
		for(int i=len;i>0;i--)
		{
			res[i] += (num1[i-1]-'0')*num2;
			res[i-1] += res[i]/10;
			res[i] %= 10;
		}
		string ss="";
		for(int i=0; i<=len; i++)
			ss += char('0' + res[i]);
		return ss;
	}
	string multiply(string num1,string num2) {
        // Note: The Solution object is instantiated only once.
		if(num1=="0" || num2=="0") return "0";
		int l1 = num1.length(),l2 = num2.length();
		string res="";
		for(int i =0; i< l2;i++)
		{
			res+='0';
			string tmp = multiplyOneBit(num1,num2[i]-'0');
			res = addTwoString(res,tmp);
		}
		res = res[0]=='0'? res.substr(1):res;
        return res;
    }

方法二:

string multiply(string num1,string num2) {
		if(num1=="0" || num2=="0") return "0";
		int l1 = num1.length(),l2 = num2.length();
		int* n1 = new int[l1];
		int* n2 = new int[l2];
		int* res = new int[l1+l2];
		memset(res,sizeof(int)*(l1+l2));
		for(int i=0; i<l1; ++i)
			n1[i] = num1[i] - '0';
		for(int i=0; i<l2; ++i)
			n2[i] = num2[i] - '0';
		
		for(int i=0; i<l1; ++i)
			for (int j=0; j<l2; ++j)
				res[i+j+1] += n1[i]*n2[j];

		string ss = "";
		for (int k=l1+l2-1; k>=0; --k){
			if(k>0) res[k-1] += res[k]/10;
			res[k] %= 10;
			ss = char(res[k]+'0')+ss;
		}
		ss = ss[0]=='0'? ss.substr(1):ss;
		//return ss.empty()?"0":ss;
		return ss;
	}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读