ZeroJudge K680: Adding and Subtracting Numbers

After defeating the Anti-Addition Beast, Feiyu encountered the Anti-Subtraction Beast!

After he thought it was just the Anti-Subtraction Beast, the Anti-Addition Beast also appeared!

Sample Inputs/Outputs

Sample Input(s)Sample Output(s)
The first line is the number of test cases.
The first line of each test case indicates whether it's a positive (+) or negative (-) test case.
The second line of each test case is an arithmetic expression.
For example: 9+9, 5-3, 2-9
Output the results of the calculations.
3

6-5
+
6+7

0-3
1
13
-3

Thought Process

Use a string to store the arithmetic expression. Run a for loop over the characters of the string. Declare an empty string and append each character to it during each iteration. If the current character is "+" or "-", convert the accumulated string and the substring starting from the current position + 1 to integers, and perform an addition or subtraction operation. Finally, output the result of the operation.

Sample Code-ZeroJudge K680: Adding and Subtracting Numbers

#include <iostream>
using namespace std;

int toint(string str)
{
    if (str.length() == 1) return int(str[0] - '0');
    return stoi(str);
}

int main() {
    cin.sync_with_stdio(0);
    cin.tie(0);
    int N;
    cin >> N;
    for (int i = 0; i<N; i++)
    {
        char op;
        cin >> op;
        string str, tmp = "";
        cin >> str;
        int ans = 0;
        for (int j = 0; j<str.length(); j++)
        {
            if (str[j] == op)
            {
                ans += toint(tmp);
                if (op == '+') ans += toint(str.substr(j+1, str.length()));
                else ans -= toint(str.substr(j+1, str.length()));
                break;
            }
            tmp += str[j];
        }
        cout << ans << "\n";
    }
}

//ZeroJudge K680
//Dr. SeanXD

Comments