FastPrepBasic Calculator II

Basic Calculator II

Snap Inc. logoSnap Inc.● MediumFULLTIMEPHONE SCREEN
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, and the expression contains no parentheses.

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 = " 3/2 "return = 1

Integer division truncates 3 / 2 toward zero.

Example 3

expression = " 3+5 / 2 "return = 5

Division is evaluated before addition, producing 3 + 2.

Constraints

  • 1 <= expression.length <= 200000.
  • After spaces are removed, the 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 Snap Inc. problems

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