leetcode 腾讯精选-43

博客给出了LeetCode上字符串相乘问题的题目链接,同时展示了相关代码,定义了宏函数max,给出了Solution类及其中的multiply函数框架。

题目:
https://leetcode-cn.com/problems/multiply-strings/
代码:
#define max(a,b) ((a)<(b))?(b):(a)
class Solution {
public:
string multiply(string num1, string num2) {

 	if (num1 == "0" || num2 == "0")
	return "0";
int length1 = num1.length();
int length2 = num2.length();
int maxlength = (length1 + 1)*(length2 + 1);
string result(maxlength,'0');

int max_length = INT_MIN;

for (int i = 0; i < length1; i++)
{
	for (int j = 0; j < length2; j++)
	{
		int l0 = num1[i] - '0';
		int l1 = num2[j] - '0';

		int b0 = result[i + j] - '0' ;
		int b1 = result[i + j + 1] - '0' ;

		int m0 = l0*l1;
		int m1 = b0*10 + b1;

		int m = m0 + m1;

		char r0 = (m / 10) + '0';
		char r1 = (m % 10) + '0';

		result[i + j] = r0 ;
		result[i + j + 1] = r1;
		max_length = max(max_length, i + j + 1);
	}
}

for (int i = max_length; i > 0; i--)
{
	int a = result[i] - '0';
	int b = result[i - 1] - '0';
	
	result[i] = (a % 10) + '0';
	result[i - 1] = ((a / 10 + b) + '0');
	
}


if (result[0] == '0')
{
	if ((max_length + 1) == 1)
	{
		return result;
	}
	else
	{
		
		return result.substr(1,max_length);
	}
}
result[max_length + 1] = '\0';
return result;

}

};

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值