Well-Formed Sum
Return True if expr is a well-formed sum, otherwise False. A well-formed sum is one or more whole numbers separated by the operators + and -, following all of these rules:
expris not empty and has digits,+and-only.- It starts with a digit and ends with a digit, so there is no leading sign and no trailing operator.
- Two operators are never next to each other.
- A number is a run of digits, and it never has a leading zero unless it is exactly
0.
So 12+5-3, 0 and 7-0+100 are well formed, while +12, 12++5, 012, 12- and 1 + 2 are not.
Example 1
expr "12+5-3"
returns true
Three numbers without leading zeros, separated by single operators.
Example 2
expr "+12"
returns false
A leading sign is not allowed.
Example 3
expr "12++5"
returns false
Two operators are next to each other, which leaves an empty number between them.
Constraints
0 <= len(expr) <= 30exprhas digits,+,-, spaces and lowercase letters only
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Strings problems
- Add the FractionsMedium
- Count and SayMedium
- Expand Character RangesMedium
- Falling DominoesMedium
- Fit the Capital PatternMedium
- Kth Letter of the Unpacked TextMedium
- Solve for xMedium
- String to IntegerMedium