Valid Number Hard 0 attempts
LeetCode ↗

Valid Number

Hard StringHash Table LeetCode

Determine whether a given string represents a valid number. Valid numbers include integers ("42"), decimals ("3.14", ".5", "2."), and scientific notation ("2e10", "3.1E-5").

A valid number optionally starts with '+' or '-', followed by digits (with an optional single decimal point), optionally followed by an exponent part ('e' or 'E' with an optional sign and digits).

Examples

Input: s = "0"       → true
Input: s = "e"       → false
Input: s = "."       → false
Input: s = ".1"      → true
Input: s = "2e10"    → true
Input: s = "-90E3"   → true
Input: s = "99e2.5"  → false (exponent must be integer)
Input: s = "1a"      → false

Constraints

  • 1 <= s.length <= 20
  • s consists of digits, '+', '-', '.', 'e', or 'E' only.
Sample Input
s = "0"
Sample Output
true
Constraints
  • 1 <= s.length <= 20
  • s consists of relevant characters
Test Cases
Case 1
Args: ["0"] 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.

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