Basic Calculator II
Updated
Problem statement
Evaluate an arithmetic expression containing non-negative integers, spaces, and the binary operators +, -, *, and /.
Calculate multiplication and division before addition and subtraction. Calculate operators with the same priority from left to right. For integer division, remove the fractional part so the result rounds toward zero. The expression contains no parentheses.
Function
calculate(expression: String) → intExamples
Example 1
expression = "3+2*2"return = 7Multiplication is evaluated first, so the result is 3 + 4 = 7.
Example 2
expression = " 3/2 "return = 1Integer division truncates 3 / 2 toward zero.
Example 3
expression = " 3+5 / 2 "return = 5Division 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. interview questions
- ID Allocator with Assign and ReleasePHONE SCREEN · Seen Nov 2026
- Stream Cluster Max and MedianPHONE SCREEN · Seen Oct 2026
- LRU Cache with Thread-Safety Follow-UpPHONE SCREEN · Seen Sep 2026
- Smallest Range Covering Elements from K ListsPHONE SCREEN · Seen Sep 2026
- Most Stones Removed with Same Row or ColumnPHONE SCREEN · Seen Sep 2026
- Report Island Areas in Discovery OrderPHONE SCREEN · Seen Aug 2026
- Render an Org Chart and Find Skip-Level PairsONSITE INTERVIEW · Seen Nov 2026
- Peak of an Increasing-Then-Decreasing ArrayONSITE INTERVIEW · Seen Oct 2026
- Number of Closed IslandsONSITE INTERVIEW · Seen Oct 2026
- Radar Barrier CrossingONSITE INTERVIEW · Seen Oct 2026
Similar questions at other companies
- Simplify a Nested Variable ExpressionGoogle · PHONE SCREEN · 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
- Stack Formula InterpreterTypeSafe AI · PHONE SCREEN
- Calculate a Token-List ExpressionCollege Vine · ONSITE INTERVIEW
- Adjacent Equal-Pair Removal GameZipRecruiter · OAZipRecruiter interview questions
- Smallest Value for a Linear Expression ModuloIntel · OA
- Adjacent Pair and Run RemovalWhatNot · PHONE SCREEN · ONSITE INTERVIEWWhatNot interview questions
- Evaluate an Arithmetic Expression Written in WordsBrex · PHONE SCREEN