LeetCode 43. Multiply Strings


两个string相乘


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

Example 1:

Input: num1 = "2", num2 = "3"
Output: "6"

Example 2:

Input: num1 = "123", num2 = "456"
Output: "56088"

Note:

  1. The length of both num1 and num2 is < 110.
  2. Both num1 and num2 contain only digits 0-9.
  3. Both num1 and num2 do not contain any leading zero, except the number 0 itself.

You must not use any built-in BigInteger library or convert the inputs to integer directly.


不要先将string转成int再进行计算,一个一个数字转成int再计算,就像小学刚开始学乘法一样。

123和456,两个三位数相乘,最长可能是6位。规律:一个n1位的数和一个n2位的数相乘,最大可能是n1+n2位数。用num[n1+n2]来存储结果。

位数    0    1    2    3    4    5    6

456*3                          1    8

                              1    6 

                       1     3

456*2                     4    8

                           4

                 1    0

456*1              1    0

                        6

                 5

结果          5    6    0    8    8 


C++版本。

string multiply1(string num1,string num2){
	int len1 = num1.length();
	int len2 = num2.length();
	int bit = len1 + len2;
	int num[200] ={0};
	
	//if(len1==0 ||len2==0) return "0";//输入限制了不能是空 
	if(num1[0]=='0'||num2[0]=='0') return "0";
	for(int i=len1-1;i>=0;i--){
		for(int j=len2-1;j>=0;j--){
			int tmp = (num1[i]-'0')*(num2[j]-'0');
			tmp += num[i+j+1];//进位
			num[i+j] += tmp/10;
			num[i+j+1] = tmp%10;
		}
	}
	int be=(num[0]==0)?1:0;
	string s(bit-be,'0');
	for(int i=0;i<bit-be;i++){
		s[i] = char(num[i+be]+'0');
	}
	return s;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值