MediumMathStringStack

Basic Calculator II

LeetCode
1 approach, code in all languages

You are given a string that encodes a simple arithmetic expression made up of non-negative integers and the operators +, -, * and /. The expression contains no parentheses, and any number of spaces may appear between tokens.

Evaluate the expression and return its integer result. Multiplication and division bind more tightly than addition and subtraction, so they must be applied before the surrounding + and - operators. Integer division truncates toward zero, meaning any fractional part is discarded rather than rounded.

You may assume the input is always a valid expression and that the final answer fits in a 32-bit signed integer.

Example 1

Input: s = "3+2*2"

Output: 7

The multiplication 2*2 is applied first to get 4, then 3+4 yields 7.

Example 2

Input: s = " 3/2 "

Output: 1

Integer division of 3 by 2 truncates toward zero, giving 1. Surrounding spaces are ignored.

Constraints

  • 1 <= s.length <= 3 * 10^5
  • s consists of integers and the operators '+', '-', '*', '/' separated by some spaces.
  • s represents a valid expression.
  • All integer values are in the range [0, 2^31 - 1].
  • The answer is guaranteed to fit in a 32-bit integer.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now