call(back)
Algorithms & Data StructuresmediumSign in to star problems

Validated Add-Subtract Calculator

Write a function that validates an arithmetic expression and, if it is valid, evaluates it. Return the result as a number, or null when the expression is invalid.

A valid expression:

  • contains only digits, + and -: no spaces, parentheses or other characters;
  • is a sequence of numbers separated by single binary operators, so it cannot be empty, cannot start or end with an operator, and cannot have two operators in a row;
  • has no number with a leading zero, except the number 0 itself;
  • has every number, and the final result, within the 32-bit signed range, -2147483648 to 2147483647.
evaluateAddSub("12-3+4")  ->  13
evaluateAddSub("0")       ->  0
evaluateAddSub("01+2")    ->  null   // leading zero
evaluateAddSub("1++2")    ->  null   // adjacent operators
evaluateAddSub("+1-2")    ->  null   // starts with an operator
evaluateAddSub("12a-3")   ->  null   // invalid character

Hints

Hint 1

Parse it as a tiny state machine: expect a number, then either the end or an operator, then a number again.

Hint 2

Check the leading-zero rule on each number's text, before converting it.

Hint 3

A number with more than ten digits is out of range without converting it at all; that also keeps the conversion exact.

Topics

Asked at

Similar Problems6