Valid Number
1 approach, code in every language
Problem description
Given a string, determine whether it represents a valid number. A valid number is an optional sign followed by either an integer or a decimal, optionally followed by an exponent part. A decimal must have digits on at least one side of the dot, an exponent begins with 'e' or 'E' followed by an optional sign and one or more digits, and any leading exponent must be preceded by a valid number.
No surrounding whitespace is allowed and no stray characters are permitted. Your job is to accept only strings that follow these rules and reject everything else.
Example 1
Input: s = "-3.14e2"
Output: true
A leading sign, a decimal part, and a valid exponent together form a well-formed number.
Example 2
Input: s = "1e"
Output: false
The exponent marker 'e' is not followed by any digits, so the string is incomplete.
Constraints
1 ≤ s.length ≤ 20s consists of English letters, digits, and the characters '+', '-', '.'The answer is a single boolean
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reading Token Validator is our own problem on the technique behind Valid Number: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free