Vasya is a student who has a younger
brother, Petya. Petya has just started first grade and began learning
arithmetic. For homework, he was given many addition and subtraction problems.
Petya asked Vasya to check his work. Seeing two pages full of problems, Vasya
was shocked by the amount of work and decided to teach Petya to use a computer
for self-checking. To do this, Vasya decided to write a program that calculates
the answers to the arithmetic problems.
Input. One line contains digits
and the symbols ‘+’ and ‘-’. The length of
the line does not exceed 104, and the value of each number in the line does not exceed 104.
Output. Print one
integer – the result of the calculation.
|
Sample
input |
Sample
output |
|
1+22-3+4-5+123 |
142 |
SOLUTION
strings
Algorithm analysis
Read the first
term into the variable res. Next, split the remaining
line into pairs: an operator symbol and a term.
![]()
Sequentially read
the pairs
(character, number) until the end of the
file, performing the corresponding operations.
Read the first term into the variable res.
scanf("%d",&res);
Read the operation sign ch (addition or subtraction), followed by an integer x. Add x to
or subtract it from the total result res.
while (scanf("%c%d", &ch, &x) == 2)
if (ch == '+') res += x; else res -= x;
Print the result of the computations.
printf("%d\n",res);
Read the first term into the variable res.
cin >> res;
Read the input data until
the end of the file. Read the operation sign ch (either addition or
subtraction) and the number x that follows it.
while (cin >> ch >> x)
Add x to res or subtract x from res.
if (ch == '+') res += x; else res -= x;
Print the result of the computations.
cout << res << endl;
Java implementation
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
String s = con.nextLine();
StringTokenizer st1 = new StringTokenizer(s, "+-");
StringTokenizer st2 = new StringTokenizer(s, "0123456789");
int res = Integer.parseInt(st1.nextToken());
while (st1.hasMoreTokens())
{
int x = Integer.parseInt(st1.nextToken());
if (st2.nextToken().equals("+")) res += x;
else res -= x;
}
System.out.println(res);
con.close();
}
}
Python implementation
Compute the
value of the input expression and print the result.
·
The eval()
function evaluates a string as a Python expression and returns the result.
print(eval(input()))