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:
Implement the parser/evaluator and make sure edge cases such as the standalone value 0 are handled correctly.