Problem J: 新奇的加法运算
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 1377 Solved: 849
[ Submit][ Status][ Web Board]
Description
定义类newInt,包括:
1. int类型的数据成员。
2. 重载运算符“+”。计算规则为:将A、B对应位置上的数字相加,只保留个位数作为结果的对应位置上的数字。比如:876 + 543 = 319。注意:该运算不改变两个操作数的值。
3. 重载输入和输出运算符,用于输入和输出对象的属性值。
4. 无参构造函数和带参构造函数。
Input
第1行N>0,表示测试用例数量。
每个测试用例包括2个非负整数,用空格隔开。
Output
见样例。
Sample Input
4876 543999 99999 1999199 88
Sample Output
876 + 543 = 319999 + 9999 = 98889 + 1999 = 1998199 + 88 = 177
HINT
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <string>
#include <vector>
#include <string.h>
using namespace std;
class newInt
{
public:
int x;
public:
newInt(int a):x(a){}
newInt(){}
~newInt(){}
friend newInt operator +(newInt a,newInt b)//首先,此处不能加const,因为传入的a,b都需要改变值;
{ //其次,不可以加&因为改变了a,b的值。main函数里面要保留其值
newInt S; //在friend newInt 后面不嫩加&如果加上则表示返回一个newInt类型的变量
int arr[100]; //而此处返回的是一个int类型!
int sum = 0;
memset(arr,0,sizeof(int));
int i = 0;
while(a.x||b.x)
{
if(a.x%10+b.x%10>9)
{
arr[i] = a.x%10+b.x%10-10;
}
else
arr[i] = a.x%10+b.x%10;
i++;
a.x = a.x/10;
b.x = b.x/10;
}
arr[i] = '\0';
for(int j = i-1;j>=0;j--)
{
sum = sum*10;
sum +=arr[j];
}
S.x = sum;
return S.x;
}
friend istream &operator >> (istream &is, newInt &b)//istream的is和b都不能随便加const,两个都需要改变值。
{
is >> b.x;
return is;
}
friend ostream &operator << (ostream &os,const newInt &b)
{
os<< b.x;
return os;
}
};
int main()
{
int cases;
newInt a, b, c;
cin>>cases;
for (int i = 0; i < cases; i++)
{
cin>>a>>b;
c = a + b;
cout<<a<<" + "<<b<<" = "<<c<<endl;
}
return 0;
}