Evaluate a Flat Addition and Subtraction Expression
Problem statement
Given expression, evaluate its decimal integer additions and subtractions from left to right and return the integer result.
For this exercise, assume the expression is valid and nonempty: an unsigned integer literal followed by zero or more binary + or - operators and unsigned integer literals. ASCII spaces may occur between tokens, and leading zeroes are interpreted as decimal. Unary signs, parentheses, multiplication, division and invalid-input handling are outside this practice contract.
For this exercise, assume a length of at most 500, literals from 0 through 1000000, and all intermediate/final results within signed 32-bit range.
Function
evaluateFlat(expression: String) → intExamples
Example 1
expression = "3+2-4"return = 1This authored expression illustrates the reported flat addition/subtraction capability and evaluates to 1.
Example 2
expression = "10 - 20 + 3"return = -7This authored example has a negative result; spaces occur between tokens.
Example 3
expression = "005 + 12 - 0007"return = 10This authored example treats leading zeroes as decimal digits.
Constraints
- For this exercise, assume
1 <= expression.length <= 500. - Every literal is a decimal integer from
0through1000000. - Only binary plus/minus and optional ASCII spaces occur; input is always syntactically valid.
- All intermediate and final values fit a signed 32-bit integer.