Valid Number

Given a string `s`, return `true` if it is a valid number. A valid number is an integer or a decimal, optionally followed by an exponent. An integer is an optional sign `+`/`-` followed by digits. A decimal is an optional sign followed by digits and a dot, a dot and digits, or digits, a dot and digits. An exponent is `e` or `E` followed by an integer. Valid: `"2"`, `"0089"`, `"-0.1"`, `"+3.14"`, `"4."`, `"-.9"`, `"2e10"`, `"-90E3"`, `"3e+7"`, `"+6e-1"`, `"53.5e93"`, `"-123.456e789"`. Not valid: `"abc"`, `"1a"`, `"1e"`, `"e3"`, `"99e2.5"`, `"--6"`, `"-+3"`, `"95a54e53"`.

30:00

Valid Number
hard
Free written solution
Topics
Companies

Given a string s, return true if it is a valid number.

A valid number is an integer or a decimal, optionally followed by an exponent. An integer is an optional sign +/- followed by digits. A decimal is an optional sign followed by digits and a dot, a dot and digits, or digits, a dot and digits. An exponent is e or E followed by an integer.

Valid: "2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789". Not valid: "abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53".

Example 1:
Input: {"s":"0"}
Output: true
Constraints:
  • 1≤s.length≤201 \leq s.\text{length} \leq 20

  • s consists only of English letters (both cases), digits, +, - and ..

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"0"}

s, coloured by the part of the number each character fills

0

0

number = [sign] digits [. digits] [e [sign] digits]

sign

+/-

digits

0-9

dot

.

fraction

0-9

exp

e/E

sign

+/-

digits

0-9

seenDigit

seenDot

seenExp

Read the string once, left to right, with three flags: seen a digit (in the current part), seen a dot, seen an exponent.

Variables
VariableValue
seenDigitfalse
seenDotfalse
seenExpfalse
DepthFunction Call
Stack empty
0/3