← 返回 uber 的题目列表Add/Sub Calculator with String Verification Follow-up
类型:online_judge
Problem: Add/Sub String Calculator (with Verification)
You are given a string s representing an arithmetic expression. The expression contains only:
Digits 0-9
Plus sign +
Minus sign -
Spaces ' ' (optional)
Your task has two steps:
String verification: determine whether s is a valid expression.
If valid, evaluate it and print the result; otherwise print INVALID.
Valid expression definition
After removing spaces, s is valid iff:
It is non-empty;
It alternates between integers and +/- operators, i.e.:
number (op number)*
A number is one or more digits (no empty numbers);
No consecutive operators are allowed (e.g. 1++2, 1+-2);
It cannot start or end with an operator (e.g. +1, 1-);
No characters other than digits, +, -, and spaces are allowed;
Note: This problem has no parentheses and no unary minus (so -1+2 is invalid).
Input/Output
Input: one line string s
Output:
If valid, output the integer result
Otherwise, output INVALID
Constraints
1 <= len(s) <= 1e5
The result fits in a 64-bit signed integer
Examples (5 tests)
Input: "1 + 2 - 3" Output: 0
Input: "10-20+5" Output: -5
Input: "1++2" Output: INVALID
Input: "-1+2" Output: INVALID
Input: " 007 + 3 " Output: 10
Example
Input
1 + 2 - 3
Output
0