sicily--1159. Sum

1.练练重载函数

2.记得之前也有一道类似的题目,同样也是在“最高进位”的问题上忘记考虑了

#include
#include
using namespace std;

class BigNum
{
public:
	BigNum()
	{
		this->num = "0";
	}
	BigNum(string n)
	{
		this->num = n;
	}
	string getNum()
	{
		return this->num;
	}

	friend BigNum operator +(const BigNum &n1, const BigNum &n2)
	{
		string temp;//和的倒置
		int carry = 0;
		//计算结果
		for(int i = n1.num.length() - 1, j = n2.num.length() - 1; i >= 0 || j >= 0; i--, j--)
		{
			if(i >= 0 && j >= 0)//两者、进位之和
			{
				temp.push_back(((n1.num[i] - 48) + (n2.num[j] - 48) + carry) % 10 + 48);//存储结果
				if((n1.num[i] - 48) + (n2.num[j] - 48) + carry > 9)//有新的进位
				{
					carry = 1;//两个十进制之和的进位不会超过1
				}
				else//没有进位
				{
					carry = 0;
				}
			}
			else//某一个数的位数已经结束
			{
				if(i >= 0)
				{
					temp.push_back(((n1.num[i] - 48) + carry) % 10 + 48);
					if((n1.num[i] - 48) + carry > 9)
					{
						carry = 1;
					}
					else
					{
						carry = 0;
					}
				}
				else//j >= 0
				{
					temp.push_back(((n2.num[j] - 48) + carry) % 10 + 48);
					if((n2.num[j] - 48) + carry > 9)
					{
						carry = 1;
					}
					else
					{
						carry = 0;
					}
				}
			}
		}
		if(carry == 1)//最高进位
			temp.push_back('1');

		//获取正确的结果
		string rev;
		bool flag = true;//去除头部的0 
		for(int i = temp.length() - 1; i >= 0; i--)
		{
			if(temp[i] == '0' && flag)
			{
				continue;
			}
			else
				flag = false;

			rev.push_back(temp[i]);
		}

		//创建一个BigNum对象,并返回
		BigNum sum(rev);
		return sum;
	}

	friend ostream& operator<<(ostream& outs, const BigNum& n)
	{
		outs << n.num;
		
		return outs;
	}
private:
	string num;
	
};

int main()
{
	int N;
	while(cin >> N && N != 0)
	{
		BigNum sum;//初始化为0
		for(int i = 1; i <= N; i++)
		{
			string s;
			cin >> s;
			BigNum temp(s);

			sum = sum + temp;
		}
		cout << sum << endl;
	}
	return 0;
}


你可能感兴趣的:(Sicily)