cswork / libraryOpen practice workspace

Coding questions · ByteDance

Build a validated add-sub calculator

This question evaluates skills in string parsing, tokenization, input validation, and safe integer arithmetic handling, with emphasis on enforcing format rules such as operator placement, prevention of leading zeros, and 32-bit signed integer bounds.

Given a string expression, write a function that validates and evaluates it.

The expression represents arithmetic using only non-negative integers and the operators + and -.

A valid expression must satisfy all of the following:

  • It contains only digits, +, and -.
  • It does not contain spaces, parentheses, or any other characters.
  • It consists of numbers separated by binary operators only, so it cannot start or end with an operator.
  • Two operators cannot appear next to each other.
  • A number cannot have leading zeros unless the number is exactly 0.
  • Every parsed number must fit in the 32-bit signed integer range.
  • The final evaluated result must also fit in the 32-bit signed integer range.

If the expression is invalid, report it as invalid. Otherwise, return the computed result.

Examples of invalid inputs include:

  • 01+2 because 01 has a leading zero
  • 1++2 because two operators are adjacent
  • +1-2 because the expression starts with an operator
  • 12a-3 because it contains an invalid character

Examples of valid inputs include:

  • 0
  • 12-3+4
  • 7+0-5

Implement the parser/evaluator and make sure edge cases such as the standalone value 0 are handled correctly.

Validated Add-Subtract Calculator

Validate and evaluate an expression containing non-negative integers with + and - only.

Hints

  1. Clarify edge cases before coding.
  2. Keep the return value deterministic.