Valid Number Hard 0 attempts
LeetCode ↗

Valid Number

Hard StringHash Table LeetCode

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.

Input Format
Implement isNumber(s). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Return the result described in the statement.

Sample Input and Output

Example 1 · Run Sample

Input
s = "0"
Output
true

Example 2

Input
s = "99e2.5"
Output
false

Example 3

Input
s = ".1"
Output
true
Constraints
  • 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)
Case 1
Args: ["0"] Expected: true
Case 2
Args: ["99e2.5"] Expected: false
Case 3
Args: [".1"] Expected: true

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.

javascript
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.

JavaScript