20分求指导
查看原帖
20分求指导
531511
leyouyuan楼主2024/12/28 13:09

代码如下

#include<cstdio>
#include<cstring>
#include<vector>
#include<iostream>

#define ch2num(x) (x - '0')
#define num2ch(x) (x + '0')
#define chline() std::cout<<std::endl
class BigInt{
private:
	int sign; // 1 as postive,-1 as negative,0 as zero
	int size;
	std::vector<int> data;
public:
	BigInt()
	{
		size = 0;
		sign = 0;
	}

	BigInt(int n)
	{
		if(n == 0)
		{
			sign = 0;
			size = 0;
			return;
		}
		sign = (n>0)? 1 : -1;
		n *= sign;
		int cnt = 0;
		while(n  >= 1)
		{	
			cnt++;
			data.push_back(n%10);
			n /= 10;
		}
		size = cnt;
	}

	BigInt(const char *s)
	{
		int len = strlen(s);
		int cnt = 0;
		for(int i = 0;i<len;i++)
		{
			if(s[i] == '-')
			{
				sign = -1;
			}
			if(s[i] == '+')
			{
				sign = 1;
			}
			else{
			data.insert(data.begin(),ch2num(s[i]));
			cnt++;
			}
		}
		size = cnt;
	}

	void print()
	{
		if(sign == -1)
		{
			putchar('-');
		}
		if(sign == 0)
		{
			putchar('0');
			return;
		}
		for(int i=size-1;i>=0;i--)
		{
			putchar(data.at(i)+'0');
		}
	}

	friend BigInt operator+(BigInt a,BigInt b);

};

void getline(char *s)
{
	char ch;
	while((ch = getchar()) != '\n')
	{
		*s = ch;
		s++;
	}
	*s = '\0';
}


int main()
{
	char s1 [300];
	char s2 [300];
	getline(s1);
	getline(s2);
	BigInt a(s1);
	BigInt b(s2);
	BigInt c = a+b;
	c.print();
	return 0;
}

BigInt operator+(BigInt a,BigInt b)
{
	if(a.sign == 0)return b;
	if(b.sign == 0)return a;
	if(a.size < b.size)return (b+a);
	BigInt ret;
	ret.sign = 1 ;	
	int nlen = a.size;
	int tmp = 0;
	int up = 0;//储存进位
	for(int i = 0;i < b.size;i++)
	{
		tmp = a.data.at(i) + b.data.at(i) + up;
		up = 0;//清空进位
		if(tmp >= 10)
		{
			up ++;
			tmp -= 10;
		}
		ret.data.push_back(tmp);
	}
	for(int i = b.size;i < a.size;i++)
	{
		tmp = a.data.at(i) + up;
		up = 0;
		if(tmp >= 10)
		{
			up ++;
			tmp -= 10;
		}
		ret.data.push_back(tmp);
	}
	ret.data.push_back(up);
	nlen += up;
	ret.size = nlen;
	return ret;
}

在本地编译完全没问题,为什么上传以后就出现问题了。

2024/12/28 13:09
加载中...