← 返回 bytedance 的题目列表Validate and Evaluate a + / - Expression (No Parentheses)
类型:online_judge
Problem: Validate and Evaluate a + / - Expression (No Parentheses)
You are given a string s representing an arithmetic expression. The expression:
Contains only digits 0-9 and binary operators + and -
Contains no parentheses and no other characters
Implement a function/program that:
Validates whether the expression is well-formed (rules below)
If valid, returns the evaluated result; otherwise returns INVALID
Validity Rules
The expression must consist of non-negative integers and operators alternating, i.e.:
num (op num)*
No empty tokens are allowed:
Cannot start with +/-
Cannot end with +/-
Cannot contain consecutive operators (e.g. "1++2", "1+-2")
Number format:
Numbers are in base-10
No leading zeros unless the number is exactly "0"
Valid: "0", "10", "101"
Invalid: "00", "01", "0123"
Range constraint:
Each parsed number must be within [MIN, MAX] (the interviewer provides the range; if unspecified, you may assume 32-bit signed [0, 2147483647])
Output
If s is valid: output the computed value (left-to-right is sufficient since only +/-)
If s is invalid: output INVALID
Examples
Input: "12+3-4" Output: 11
Input: "0+0" Output: 0
Input: "01+2" Output: INVALID
Input: "1+" Output: INVALID
Input: "1--2" Output: INVALID
Constraints
1 <= len(s) <= 1e5
Target time O(n); space O(1) or O(n) is acceptable.
Example
Input
12+3-4
Output
11