Diwali Offer!Flat 20% OFF
Enroll Now
PrakalpanaLive online tech training

95. Basic Calculator II

MediumDay 27 of 60Stack & Queue

Given a string s holding a valid expression with non-negative integers, the operators +, -, *, / and spaces, evaluate it and return the integer result. Multiplication and division bind tighter than addition and subtraction, and division truncates toward zero. There are no parentheses, and you may not use built-in expression evaluators such as eval().

Example 1
Input: s = "3+2*2"
Output: 7
2*2 is done first, then 3 + 4.
Example 2
Input: s = " 3+5 / 2 "
Output: 5
5 / 2 = 2, then 3 + 2.
Constraints
  • 1 <= s.length <= 3 * 10^5
  • All numbers are in [0, 2^31 - 1]
  • The answer and every intermediate value fit in a 32-bit integer
  • The expression is valid
Hints
Frequently asked at: Meta, Amazon, Microsoft, Uber
Ctrl + Enter runs the examples

Not sure what to learn next?

A 1-on-1 session with an industry mentor and a roadmap built for you. How it works

  1. 1Discuss your goals
  2. 2Get a personal plan
  3. 3Start learning
Book for β‚Ή200/ 30 min