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
0itself; - has every number, and the final result, within the 32-bit signed range,
-2147483648to2147483647.
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 characterHints
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
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.