Calculator#1427

Calculator (Editorial)

Read the first term into the variable . 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.

Algorithm implementation

Read the first term into the variable .

scanf("%d",&res);

Read the operation sign (addition or subtraction), followed by an integer . Add to or subtract it from the total result .

while (scanf("%c%d", &ch, &x) == 2)
  if (ch == '+') res += x; else res -= x;

Print the result of the computations.

printf("%d\n",res);

Algorithm implementation — iostream

Read the first term into the variable .

cin >> res;

Read the input data until the end of the file. Read the operation sign (either addition or subtraction) and the number that follows it.

while (cin >> ch >> x)

Add to or subtract from .

  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.

print(eval(input()))