Problem D: a novel addition operation

Description

Define the class newInt, including:

  1. Data member of type int.
  2. Overloaded operator '+'. The calculation rule is: add the numbers in the corresponding positions of A and B, and only keep one digit as the number in the corresponding position of the result. For example: 876 + 543 = 319. Note: this operation does not change the value of two operands.
  3. Overloads input and output operators, which are used to input and output property values of objects.
  4. Parameterless and parameterless constructors.

Input

Line 1, n > 0, indicates the number of test cases.
Each test case consists of two non negative integers separated by spaces.

Output

See Example

Sample Input

4
876 543
999 9999
9 1999
199 88

Sample Output

876 + 543 = 319
999 + 9999 = 9888
9 + 1999 = 1998
199 + 88 = 177

HINT

You cannot use characters such as string, char, or string types.

Append Code

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;
}

Sample Code

#include<iostream>
 
using namespace std;
 
class newInt
{
    int i;
public:
    newInt operator+(newInt &n)
    {
        int x=i;
        int y=n.i;
        int s=0;
        //Take the number of digits of the longer digit as the number of cycles
        if(x>=y)
        {
            int a=x,l=1,mode=1;
            a/=10;
            while(a) //Find the number of digits of the longer number
            {
                a/=10;
                l++;
            }
            for(int j=0;j<l;j++)
            {
                s+=((x%10+y%10)%10)*mode;
                mode*=10;
                x/=10;
                y/=10;
            }
        }
        else
        {
            int a=y,l=1,mode=1;
            a/=10;
            while(a) //Find the number of digits of the longer number
            {
                a/=10;
                l++;
            }
            for(int j=0;j<l;j++)
            {
                s+=((x%10+y%10)%10)*mode;
                mode*=10;
                x/=10;
                y/=10;
            }
        }
        return newInt(s);
    }
    friend istream& operator>>(istream &is,newInt &n)
    {
        is>>n.i;
        return is;
    }
    friend ostream& operator<<(ostream &os,const newInt &n)
    {
        os<<n.i;
        return os;
    }
    newInt(int a=0):i(a){}
};
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;
}

Posted by jingato on Mon, 18 Nov 2019 08:00:59 -0800