1. Problem Statement (Simplified)
You’re given a string s.
You must determine whether s is a valid number, according to these rules:
Valid forms include e.g.:
Integers: "2", "0089", "-0", "+10"
Decimals: "-0.1", "+3.14", "4.", "-." (not valid), "-.9", etc.
With exponent (scientific notation): "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"
Examples of invalid numbers: "abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53", ".", "e"
Roughly, valid number:
[optional sign] + [integer or decimal]
[optional exponent] – if exponent exists: 'e' or 'E' + [optional sign] + [digits]
2. Parsing Strategy – Single Pass with Flags
We parse string s from left to right and track:
seenDigit – have we seen any digit before exponent?
seenDot – have we seen a decimal point?
seenExp – have we seen exponent e or E?
seenDigitAfterExp – have we seen any digit after exponent?
Rules while scanning:
For each character c:
Digit ('0'..'9'):
seenDigit = true
If we already saw exponent (seenExp == true), also set seenDigitAfterExp = true.
Dot ('.'):
Valid only if:
We haven’t seen a dot before (!seenDot)
We haven’t seen exponent before (!seenExp)
Otherwise → invalid.
Exponent ('e' or 'E'):
Valid only if:
We haven’t seen exponent before (!seenExp)
We have already seen at least one digit before exponent (seenDigit)
Then:
seenExp = true
seenDigitAfterExp = false (we must see digits after exponent).
Sign ('+' or '-'):
Valid only at:
Beginning of the string (i == 0)
Immediately after exponent (s[i-1] == 'e' || s[i-1] == 'E')
Otherwise → invalid.
Anything else → invalid.
After scanning all characters:
Must have:
seenDigit == true
AND if exponent exists, seenDigitAfterExp == true (so exponent part must have at least one digit).
If those are satisfied → true, else false.
Pseudo-code:
3. Edge Cases to Consider
Only sign: "+", "-" → invalid (no digits).
Only dot: "." → invalid.
Sign with dot but no digits: ".", "+.", "-." → invalid (no digits).
Dot with digits: "0.", ".1", "3.", "3.5" → valid.
Exponent:
"1e", "e3" → invalid.
"1e+", "1e-" → invalid (no digits after sign).
"1e10", "1E-10" → valid.
No spaces are allowed by the problem statement, so we do not need to trim or handle spaces.
4. Java code
7. Python code
8. JavaScript code






Comments
Post a Comment