Valid Number
Check whether a given string qualifies as a well-formed number. That covers plain integers ("42"), decimal values ("3.14", ".5", "2."), and numbers written in scientific notation ("2e10", "3.1E-5").
Structurally, a valid number may begin with a '+' or '-' sign, then a run of digits that can contain at most one decimal point, and may optionally end with an exponent — an 'e' or 'E' followed by an optional sign and more digits.
Sample Input and Output
Example 1 · Run Sample
s = "0" true Example 2
s = "99e2.5" false Example 3
s = ".1" true - 1 <= s.length <= 20
- s contains ASCII letters, decimal digits, plus, minus, or dot; letters other than e/E invalidate the number.
Test Cases (3)
Walk through the string character by character, tracking three boolean flags: whether a digit has been seen, whether a dot has been seen, and whether an exponent has been seen. Apply the rules at each character — signs are only valid at the start or right after e/E, dots can't appear after an exponent, and e/E requires a preceding digit.
function isNumber(s) {
let seenDigit = false;
let seenDot = false;
let seenE = false;
for (let i = 0; i < s.length; i++) {
const ch = s[i];
if (ch >= '0' && ch <= '9') {
seenDigit = true;
} else if (ch === '+' || ch === '-') {
if (i > 0 && s[i - 1] !== 'e' && s[i - 1] !== 'E') return false;
} else if (ch === '.') {
if (seenDot || seenE) return false;
seenDot = true;
} else if (ch === 'e' || ch === 'E') {
if (seenE || !seenDigit) return false;
seenE = true;
seenDigit = false;
} else {
return false;
}
}
return seenDigit;
}Time: O(n) — single pass through the string. Space: O(1) — only boolean flags.
Saved in this browser only. Private to you.