Skip to problem
←

Valid Number

Hard 0 attempts

Return whether the entire string s is a valid number under these rules:

  1. Start with an optional + or - sign.
  2. Follow it with an integer or decimal containing at least one digit. A decimal has exactly one dot and may omit digits on either side, but not both: "4.", ".5", and "4.5" are valid; "." is not.
  3. Optionally append e or E, an optional sign, and one or more digits. The exponent must be an integer, so "1e2.5" is invalid.

Leading zeros are allowed. Other letters are invalid, including "NaN", "Infinity", and hexadecimal notation such as "0x10". Inputs contain no whitespace.

Check syntax only, not numerical magnitude: "1e999" is valid even though its value exceeds the finite range of a JavaScript Number. Return a boolean, not a parsed number.

Function contract

Implement isNumber(s).

Output: Return true if the entire string matches the numeric syntax in the statement; otherwise return false.

Example 1

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

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.

Reset the digit flag when encountering an exponent so a trailing e, E, or exponent sign cannot pass the final check. Do not use numeric conversion as the validator: its accepted forms and range differ from this grammar.

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.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript