【洛谷】P2142 高精度减法

#include<bits/stdc++.h>
using namespace std;
struct bign{
	int len; string s;
	void length(){
		len = s.length();
	}
	bign operator - (const bign x) const
	{
		bign ret,a1,a2;
		a1.len = len; a1.s = s;
		a2.len = x.len; a2.s = x.s;
		int l = a1.len;
		if (a1.len > a2.len)
		{
			for (int i = 1 ; i <= a1.len- a2.len ; i ++) a2.s = '0'+a2.s;
		}
		for (int i = l - 1 ; i >= 0 ; i --)
		{
			if (a1.s[i] < a2.s[i])
			{
				a1.s[i] = char(a1.s[i]+10);
				a1.s[i-1] = char(a1.s[i-1]-1);
			}
			ret.s = char(a1.s[i]-a2.s[i] + 48) + ret.s;
		}
		while (ret.s[0] == '0' && ret.s.length() > 1) ret.s.erase(0,1);
		ret.len = ret.s.length();
		return ret;
	}
}a,b;

bool cmp(bign x,bign y)
{
	
	if (x.len > y.len) return 0;
	if (x.len < y.len) return 1;
	for (int i = 0 ; i < x.len ; i ++)
	{
		if (x.s[i] > y.s[i]) return 0;
		if (x.s[i] < y.s[i]) return 1;
	}
	return 0;
}
int main()
{
	getline(cin,a.s);
	getline(cin,b.s);
	a.length(); b.length();
	if (cmp(a,b)) 
	{
		swap(a,b);
		cout<<'-';
	}
	a = a - b;
	cout<<a.s<<endl; 
	return 0;
}

  自己写的,重载运算符版,哈哈~

posted @ 2017-12-16 09:27  surpassion  阅读(296)  评论(0编辑  收藏  举报