高精度

高精度减法

#include <bits/stdc++.h>

using namespace std;



bool cmp(vector<int>a, vector<int>b)
{
    if(a.size() != b.size())    return a.size() > b.size();
    for(int i = a.size() - 1; i >= 0; -- i)
        if(a[i] != b[i])    return a[i] > b[i];
    return true;
}

vector<int> sub(vector<int>a, vector<int>b)
{
    vector<int>ans;
    for(int i = 0, t = 0; i < a.size(); ++ i)
    {
        t = a[i] - t;
        if(b.size() - 1 >= i)   t -= b[i];
        ans.push_back((t + 10) % 10);
        if(t < 0) t = 1;
        else t = 0;
    }
    while(ans.size() != 1 && ans.back() == 0)   ans.pop_back();
    return ans;
}

void run()
{
	int n;
	string A, B;
	vector<int>a, b, c;
	cin >> n;
	cin >> A;
    for(int i = A.size() - 1; i >= 0; -- i) a.push_back(A[i] - '0');
    for(int i = n - 1; i >= 0; -- i) b.push_back(9);
    for(int i = n; i >= 0; -- i)	c.push_back(1);
    vector<int> ans1 = sub(b, a);
	vector<int> ans2 = sub(c, a);
	if(ans1.size() == n)
	{
		for(int i = ans1.size() - 1; i >= 0; -- i)	cout << ans1[i];
		cout << endl;
		return;
	}
	for(int i = ans2.size() - 1; i >= 0; -- i)	cout << ans2[i];
	cout << endl;
}

int main()
{
//	freopen("1.in", "r", stdin);
	int t;cin >> t;
	while(t --)	run();
	return 0;
    
}
posted @ 2023-04-30 21:56  cxy8  阅读(18)  评论(0编辑  收藏  举报