oneby7

Stacks and Queues Matching and cancelling

203. Basic Calculator II

Medium

You are given a string s that holds an arithmetic expression. Return its value.

The expression is made of non-negative integers and the four operators +, -, * and /. Any number of spaces can sit between them, and at the start and the end. There are no brackets and no negative numbers.

Calculate it with the usual rules: * and / are applied before + and -, and operators at the same level are applied from left to right. So 2 + 3 * 4 is 14, and 8 / 2 * 3 is 12. Division between integers drops the remainder, which means it truncates toward zero: 7 / 2 is 3.

Do not use a built-in function that evaluates a string as an expression, such as eval.

Example 1

Input: s = "4 + 18 / 3 * 2 - 5"

Output: 11

Explanation: * and / come first, from left to right: 18 / 3 = 6, then 6 × 2 = 12. That leaves 4 + 12 − 5, which is 11.

Example 2

Input: s = " 14-3/2 "

Output: 13

Explanation: The spaces at the start and the end change nothing. 3 / 2 is 1.5, and dropping the remainder gives 1. Then 14 − 1 = 13.

Example 3

Input: s = "2147483647 * 2 + 1"

Output: 4294967295

Check your understanding

Work out the answer for this input before you write any code.

s = "8-6/2*3"

Constraints

  • 1 ≤ s.length ≤ 3 × 105
  • s holds only digits, spaces and the characters '+', '-', '*' and '/'
  • s is a valid expression: ignoring spaces, it starts and ends with a number, and numbers and operators take turns. No space falls inside a number.
  • Every number is between 0 and 231 − 1, written in decimal with no leading zeros
  • No division has a divisor of 0
  • Calculated with the usual rules, the result of every operation is between -1015 and 1015

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.