KatInterview

Left-to-Right Calculator Using Only Scalar State

StringsAuto-graded · 22 test cases
MediumAuto-gradedStringsstring-parsingtwo-pointerssimulation

Last updated

Evaluate a no-parentheses arithmetic string with correct precedence and truncating division in one pass, using only a few scalar variables instead of a stack.

Left-to-Right Calculator Using Only Scalar State

You are given a string expr containing a well-formed arithmetic expression. It consists of non-negative integers, the operators +, -, *, /, and space characters. There are no parentheses and no unary signs.

Compute the value of the expression and return it as an integer.

Rules

  • * and / have higher precedence than + and -.
  • Operators of equal precedence are applied from left to right. For example, 8/2*3 means (8/2)*3, which is 12.
  • Division is integer division that truncates toward zero. So 7/2 is 3, and a negative intermediate value such as -7 divided by 2 gives -3 (not -4).
  • Operands can have several digits. Spaces may appear at the start, at the end, or between tokens, and carry no meaning.
  • The expression is always valid and never divides by zero.

Implementation requirement

Solve it in a single left-to-right pass, in O(n) time and O(1) extra space. Do not use an explicit stack (or any list/collection that grows with the input), and do not use recursion. A handful of integer variables is all you should need.

Constraints

  • expr contains only digits, +, -, *, /, and spaces.
  • The expression is valid: it contains at least one number, and operators sit between numbers.
  • No division by zero occurs.
  • All intermediate and final values fit comfortably in Python integers; compute exactly with integer arithmetic (avoid floating point).

Examples

Example 1

Input: calculate_no_stack('3+2*2')

Output: 7

Example 2

Input: calculate_no_stack(' 3/2 ')

Output: 1

Example 3

Input: calculate_no_stack(' 3+5 / 2 ')

Output: 5

Hints

Hint 1

Only the most recent additive term can still be changed by a following `*` or `/`. Everything before it is final, so you can keep a running total of finished terms plus one 'open' term.

Hint 2

Process a number only when you reach the next operator (or the end of the string), and apply the operator that came BEFORE that number. Reset the number being built after each operator, and make sure the last number is flushed too.

Hint 3

For `+` and `-`, add the open term into the total and start a new open term with the signed number. For `*` and `/`, update the open term in place. For division, divide absolute values and restore the sign to get truncation toward zero.