大数相乘(字符串存储)

本文介绍了一种手动模拟字符串相乘的算法实现,通过使用C++编程语言,详细展示了如何处理两个大数的乘法运算。算法首先检查输入是否为零,然后利用数组进行逐位相乘和进位处理,最后将结果转换为字符串形式返回。

手动模拟字符串相乘

#include<iostream>
#include<string>
#include<vector>
using namespace std;
class Solution {
	public:
		string multiply(string num1, string num2) {  // 字符串相乘
			if (num1 == "0" || num2 == "0")	{
				return "0";
			}

			int m = num1.size(), n = num2.size();
			auto ansArr = vector<int>(m + n);

			for (int i = m - 1; i >= 0; --i) {
				int x = num1.at(i) - '0';
				for (int j = n - 1; j >= 0; --j) {
					int y = num2.at(j) - '0';
					ansArr[i + j + 1] += x * y;
				}
			}

			for (int i = m + n - 1; i > 0; i--) {
				ansArr[i - 1] += ansArr[i] / 10;
				ansArr[i] %= 10;
			}

			int index = ansArr[0] == 0 ? 1 : 0;

			string ans;
			while (index < m + n) {
				ans.push_back(ansArr[index]);
				index++;
			}
			for (auto &c : ans) {
				c += '0';
			}
			return ans;
		}
};

int main() {
	string a,b;
	cin>>a>>b;
	Solution ss;
	cout<<ss.multiply(a,b);
}

结果

在这里插入图片描述

思考扩展

如果有符号呢?只需要加flag位记录符号就可以了,这里就不贴出代码了

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值