跳到正文

题解

题解:P1001 A+B Problem

Shellchen约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟
题目
P1001

版本

  1. v1当前

一篇高精度题解。

注意特判正负数和 0。

C++
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N=2e5+10,mod=1e9+7;
int a[N],b[N],c[N];
void to_big(string s,int a[])
{
	a[0]=s.size();
	for(int i=0;i<a[0];i++) a[a[0]-i]=s[i]-'0';
}
void add(int a[],int b[],int c[])
{
	c[0]=max(a[0],b[0]);
	int u=0;
	for(int i=1;i<=c[0];i++)
	{
		int t=u;
		if(i<=a[0]) t+=a[i];
		if(i<=b[0]) t+=b[i];
		c[i]=t%10;
		u=t/10;
	}
	if(u) c[++c[0]]=u;
}
void sub(int a[],int b[],int c[])
{
	c[0]=a[0];
	int u=0;
	for(int i=1;i<=c[0];i++)
	{
		int t=-u;
		t+=a[i];
		if(i<=b[0]) t-=b[i];
		if(t<0) c[i]=t+10,u=1;
		else c[i]=t,u=0;
	}
	while(c[c[0]]==0&&c[0]>1) c[0]--;
}
void print(int a[])
{
	for(int i=a[0];i>=1;i--) cout<<a[i];
}
bool cmp(int a[],int b[])
{
	if(a[0]!=b[0]) return a[0]<b[0];
	for(int i=a[0];i>=1;i--) if(a[i]!=b[i]) return a[i]<b[i];
	return 1;
}
signed main()
{
	string x,y;
	cin>>x>>y;
	if(x[0]=='0') cout<<y;
	else if(y[0]=='0') cout<<x;
	else if(x[0]=='-')
	{
		x.erase(0,1);
		if(y[0]=='-')
		{
			y.erase(0,1);
			to_big(x,a);
			to_big(y,b);
			add(a,b,c);
			cout<<'-';
			print(c);
		}
		else
		{
			to_big(x,a);
			to_big(y,b);
			if(cmp(a,b))
			{
				sub(b,a,c);
				print(c);
			}
			else
			{
				sub(a,b,c);
				cout<<'-';
				print(c);
			}
		}
	}
	else
	{
		if(y[0]=='-')
		{
			y.erase(0,1);
			to_big(x,a);
			to_big(y,b);
			if(cmp(a,b))
			{
				sub(b,a,c);
				cout<<'-';
				print(c);
			}
			else
			{
				sub(a,b,c);
				print(c);
			}
		}
		else
		{
			to_big(x,a);
			to_big(y,b);
			add(a,b,c);
			print(c);
		}
	}
    return 0;
}
原文