Skills101
← All coding problems

Basic Calculator

hardLinked List & Stack II+40 XPTime limit 2s

Build the brain of a simple calculator. Evaluate an expression made of non-negative integers, +, -, parentheses ( ) and spaces. A - may also be a unary minus — at the very start of the expression or right after ( — as in -(2+3) or (-4+1). Do not use any built-in eval.

Input: one line, a valid expression.

Output: its value.

Constraints: 1 ≤ length ≤ 2·10⁵; every number in the expression is at most 2³¹ − 1; the result and every intermediate value fit in a 64-bit signed integer (use long / long long). Parentheses can be nested up to 10⁴ levels deep.

Think about it: with only + and -, the answer is a sum of numbers with signs. Keep a running result and the current sign. On (, push the current result and sign onto a stack and start fresh; on ), finish the inner value, pop, and combine: result = saved + savedSign × inner. Deep nesting makes recursion risky — the stack version is safe.

Sample input 1

1 + 1

Sample output 1

2

Sample input 2

2-1 + 2

Sample output 2

3

Sample input 3

(1+(4+5+2)-3)-(6+8)

Sample output 3

-5

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.