Multiply Strings--LeetCode

本文介绍了一种处理大数相乘的算法实现方法,利用字符串来表示任意大小的整数,并通过逐位相乘的方式得出结果。适用于超出常规整型变量范围的大数运算场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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.

思路:大数相乘 使用字符串表示

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

/*
大数相乘  大数使用字符串表示 同时不用考虑负数
 
*/
/*
思路:对于结果页使用字符串表示,两个数相乘的结果长度不可能比两个数长度的和还要长 
*/ 
int multiply(char a,char b)
{
	int first = a-'0';
	int second = b -'0';
	return first*second;
}
string MultiplyStrings(string& first,string& second)
{
	int len1 = first.length();
	int len2 = second.length();
	string result(len1+len2,'0');
	int i,j;
	int carry=0;
	int tmp,tmp1,pos;
	for(i=len2-1;i>=0;i--)
	{
		carry =0;
		for(j=len1-1;j>=0;j--)
		{
			pos = len1-1+len2-1-i-j;
			tmp = multiply(first[j],second[i]);
			tmp1= (tmp%10 + carry+result[pos]-'0');
			result[pos] = (char)(tmp1%10 +'0');
			cout<<"pos is "<<pos<<" tmp is "<<tmp<<" tmp1 is "<<tmp1<<" i+j is "<<result[pos]<<endl;
			carry = tmp/10+tmp1/10;			
		}
	}
	
	result.assign(result.begin(),result.begin()+pos+1);
	reverse(result.begin(),result.end());
	return result;
}

int main()
{
	string first("12345678");
	string second("12345678");
	string result = MultiplyStrings(first,second);
	cout<<result<<endl; 
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值