Valid Number with Exponents
Problem statement
Given a string s, return true if the entire string represents a valid number under the following grammar, or false otherwise. Validate the spelling; do not convert it to a numeric type.
- The mantissa may begin with one optional
+or-sign. - After that sign, the mantissa is either one or more digits with an optional decimal point and zero or more following digits, or a decimal point followed by one or more digits.
- The mantissa may be followed by one exponent:
eorE, an optional+or-sign, and one or more digits. Decimal points are not allowed in the exponent. - Digits are the ASCII characters
0through9. No whitespace or other characters are allowed in a valid number.
For example, 7, -7., +.5, and 7e-2 are valid. The empty string, ., and 7e are invalid. Leading zeros and arbitrarily large magnitudes are allowed within the input length limit.
Function
isNumber(s: String) → booleanExamples
Example 1
s = "-12.5e+2"return = trueThe mantissa -12.5 has an optional minus sign and digits on both sides of its decimal point. The exponent e+2 has a marker, an optional plus sign, and a digit. The whole string follows the grammar.
Example 2
s = ".4"return = trueA mantissa may start with a decimal point when at least one digit follows it. The digit 4 satisfies that requirement, and an exponent is optional.
Example 3
s = "4e+"return = falseThe mantissa 4 is valid, but the exponent has a marker and a sign with no digit after them.
Constraints
0 <= s.length <= 10000.- Each character in the input is printable ASCII, with a code from 32 through 126.
- Inputs need not be valid numbers; return false for any spelling outside the grammar.