A*B问题

计算两个非负整数 A,BA,B 的乘积,A,BA,B 可能会很大。

输入格式

第一行输入一个非负整数 AA

第二行输入一个非负整数 BB

A,BA,B 的长度不大于 500500

输出格式

输出 A\times BA×B 的值。

样例输入

4321
1234

样例输出

5332114

/**
 * 基本思路就是让第一个数的每一位去乘以第二个数,然后累加更新
 * 特判是0乘以任何数都是0
 */
#include <bits/stdc++.h>
using namespace std;
string reverse(string s) {
	string cas = "";
	for (int i = s.length()-1; i >= 0; i--) {
		cas += s[i];
	}
	return cas;
}
int c[505*505] = {0};//数组得开得大一点
int main()
{
	string str1, str2;
	cin >> str1;
	cin >> str2;

	str1 = reverse(str1);
	str2 = reverse(str2);
	if (str1 == "0" || str2 == "0") {
		printf("0\n");
	} else {
		int index = 0;
		int cnt = 0;
		for (int i = 0; i < str1.length(); i++) {
			int num = str1[i] - '0';//取第一个数的每一位与第二个数相乘,每次累加
			index = 0+cnt;
			int k = 0;
			for (int j = 0; j < str2.length(); j++) {
				int op = num*(str2[j] - '0') + k;
				int temp = (c[index] + op);
				c[index] = temp%10;
				index++;
				k = temp/10;
			}
			if (k != 0) {
				c[index] = c[index] + k;
				index++;
			}
			cnt++;
		}
		for (int i = index-1; i >= 0; i--) {
			printf("%d", c[i]);
		}
		printf("\n");
	}
	return 0;
}

//类似的如果求A+B,就是用数组来存

#include <bits/stdc++.h>
using namespace std;
string reverse(string s) {
	string cas = "";
	for (int i = s.length()-1; i >= 0; i--) {
		cas += s[i];
	}
	return cas;
}
int main() {
	string str1, str2;
	cin >> str1;
	cin >> str2;
	int c[505];
	int len = str1.length() < str2.length() ? str1.length():str2.length();
	str1 = reverse(str1);
	str2 = reverse(str2);
	//check
	// cout << str1 << endl;
	// cout << str2 << endl;
	//cal
	int index = 0;
	int k = 0;
	for (int i = 0; i < len; i++) {
		int op = (str1[i]-'0') + (str2[i]-'0') + k;
		c[index++] = op%10;
		k = op/10;
	}


	//
	if (str1.length() > len) {
		for (int i = len; i < str1.length(); i++) {
			int op = (str1[i]-'0') + k;
			c[index++] = op%10;
			k = op/10;
		}
		if (k != 0) c[index++] = k;
	} else {
		for (int i = len; i < str2.length(); i++) {
			int op = (str2[i]-'0') + k;
			c[index++] = op%10;
			k = op/10;
		}
		if (k != 0) c[index++] = k;
	}

	for (int i = index-1; i >= 0; i--) {
		printf("%d", c[i]);
	}
	printf("\n");
	return 0;
}
    原文作者: 汉诺塔问题
    原文地址: https://blog.csdn.net/qq_34649947/article/details/79266307
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞