Basic Calculator II
Updated
Problem statement
Given a string s that holds an arithmetic expression, evaluate it and return its value.
The expression is made of non-negative integers and the operators +, -, * and /. Spaces may appear before, between or after the numbers and operators. There are no parentheses, and every operator stands between two numbers.
Use the usual order of operations: * and / come before + and -, and operators of the same level are applied from left to right. Integer division truncates toward zero, so any fractional part is dropped.
Do not use a built-in function that evaluates a string as an expression, such as eval().
Function
calculate(s: String) → intExamples
Example 1
s = "2+3*4"return = 14Multiplication comes first: 3*4 = 12, then 2 + 12 = 14.
Example 2
s = " 10 - 7 / 2 "return = 77 / 2 is 3.5, which truncates to 3. Then 10 - 3 = 7. The spaces do not matter.
Example 3
s = "8/3*3 - 6/4"return = 5Operators of the same level go from left to right: 8/3 = 2, then 2*3 = 6. Also 6/4 = 1, so the answer is 6 - 1 = 5.
Constraints
1 <= s.length <= 10^5scontains only digits, the operators+,-,*,/and spaces.sis a valid expression: with the spaces removed, it is one number, followed by zero or more pairs of an operator and a number.- Every number in
sis between0and2^31 - 1, and no divisor is0. - The answer and every intermediate result fit in a signed 32-bit integer (from
-2^31to2^31 - 1).
More TypeSafe AI interview questions
Similar questions at other companies
- Adjacent Equal-Pair Removal GameZipRecruiter · OAZipRecruiter interview questions
- Smallest Value for a Linear Expression ModuloIntel · OA
- Calculate a Token-List ExpressionCollege Vine · ONSITE INTERVIEW
- Basic Calculator IISnap Inc. · PHONE SCREENSnap Inc. interview questions
- Basic Calculator II With Empty InputGoogle · ONSITE INTERVIEWGoogle interview questions
- Evaluate Arithmetic with Operator PrecedenceRoblox · PHONE SCREENRoblox interview questions
- Simplify a Formula with Known and Unknown VariablesBetter.com · PHONE SCREEN
- Evaluate Parenthesized Addition and SubtractionAtlassian · PHONE SCREENAtlassian interview questions
- Compress Editor Actions into Operational Transform OperationsReplit · OA · PHONE SCREEN · ONSITE INTERVIEW
- Perfect Squares Matching a PatternNielsen · OA