FastPrepBasic Calculator II With Empty Input

Basic Calculator II With Empty Input

Google logoGoogle● MediumNEW GRADONSITE INTERVIEW
Learn

Problem statement

Evaluate an arithmetic expression containing non-negative integers, spaces, and the binary operators +, -, *, and /. Multiplication and division have higher precedence than addition and subtraction; operators with the same precedence are evaluated from left to right.

Integer division truncates toward zero. The expression contains no parentheses. If expression is empty or contains only spaces, return 0.

Function

calculate(expression: String) → int

Examples

Example 1

expression = "3+2*2"return = 7

Multiplication is evaluated first, so the result is 3 + 4 = 7.

Example 2

expression = " 14-3/2 "return = 13

3 / 2 truncates to 1, giving 14 - 1.

Example 3

expression = "   "return = 0

A spaces-only expression is the explicit empty case.

Constraints

  • 0 <= expression.length <= 200000.
  • After spaces are removed, a non-empty expression alternates non-negative base-10 integers and operators from +, -, *, and /.
  • No divisor is zero.
  • Every intermediate and final result fits a signed 32-bit integer.

More Google problems

See Google hiring insights
public int calculate(String expression) {
    // write your code here
}
expression"3+2*2"
expected7
Checking account…