小米oj #3.大数相减 高精度减法

题目链接https://code.mi.com/problem/list/view?id=3
描述

两个长度超出常规整形变量上限的大数相减,请避免使用各语言内置大数处理库,如 Java.math.BigInteger 等。

输入

有 N 行测试数据,每一行有两个代表整数的字符串 a 和 b,长度超过百位。规定 a>=b,a, b > 0。 测试结果可以用 linux 小工具 bc进行测试是否正确。

输出

返回表示结果整数的字符串。

输入样例

1231231237812739878951331231231237812739878951331231231237812739878951331231231237812739878951331231231237812739878951331231231237812739870-89513312312312378127398789513312312312378127398789513312312312378127398789513
1231231237812739878951331231231237812739878951331231231237812739878951331230000000000000000000000001-331231231237812739878951331231231

输出样例

1231231237812739878951331231231237812739878951331231231237812650365639018918853110413950365639018918853110413950365639018918853110413950357
1231231237812739878951331231231237812739878951331231231237812739878620099998762187260121048668768770

题目分析

答案一定为正数,免去了很多判断
我是模拟算的,也可以用python过


#include<iostream>
#include<map>
#include<string>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn = 2e6 + 10;

string a, b,s;
bool flag;
int an[maxn],bn[maxn];

string jian(string a,string b){
	memset(an, 0, sizeof an), memset(bn, 0, sizeof bn);
	for (int i = 0; i < a.length(); i++) an[a.length() - 1 - i] = a[i] - '0';
	for (int i = 0; i < b.length(); i++) bn[b.length() - 1 - i] = b[i] - '0';
	
	int len = a.length();//因为a>=b
	for (int i = 0; i < len; i++){
		an[i] -= bn[i];
		if (an[i] < 0) an[i] += 10, an[i + 1] -= 1;
	}
	if (!an[len - 1]) len--;
	string res="";
	for (int i = 0; i < len; i++)
		res += an[len-1-i]+'0';
	return res;
}
int main()
{
	ios::sync_with_stdio(false);
	while (cin >> s){
		a = "", b = "";
		flag = false;
		for (int i = 0; i < s.length(); i++){
			if (s[i] == '-')
			for (int j = i + 1; j < s.length(); j++){
				b += s[j];
				flag = true;
			}
			if (flag == true) break;
			a += s[i];
		}
		cout << jian(a, b) << endl;
	}
	return 0;
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Mr_HCW/article/details/88626292
今日推荐