← Questions

Valid number: decide whether a string is a decimal number

0
MetaCodingLast asked Apr 2026

Return whether a string is a valid decimal number. Write down the exact rules first, then implement them cleanly.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • is_number(s: str) -> bool — after trimming leading and trailing spaces, the whole string must match:
    • number := sign? (digits '.' digits? | '.' digits | digits) exponent?
    • exponent := ('e' | 'E') sign? digits
    • sign := '+' | '-'; digits := one or more of 0-9

Example

valid:    "0"  "-3.14"  "+.8"  "2e10"  "-1.2E-3"  "4."  "3e+7"
invalid:  "abc"  "1a"  "e9"  "."  "+"  "1e"  "--6"  "1e2.5"

Constraints

  • 1 <= len(s) <= 20; letters, digits, +, -, ., spaces.

Clarifying questions

  • Are leading and trailing spaces allowed? Spaces inside?
  • Is "4." valid? ".5"? "."?
  • Can the exponent be fractional or signed?
  • Are hexadecimal, "inf" or "NaN" in scope?

What a strong answer covers

  • The grammar stated before any code, agreed with the interviewer.
  • A single pass with flags (seen_digit, seen_dot, seen_exp, digit_after_exp): a sign only at the start or right after e; a dot only before any e and only once; e only once and only after a digit; at least one digit after e.
  • Or an explicit finite-state machine with named states, which is easier to extend and test.
  • Why a library call or a regular expression may not be acceptable, and how to test the parser against a table of cases.
  • Tests: each rule's boundary, such as ".", "e", "+e1", "1e+", " 1 ".

Follow-ups

  • Return the parsed value as well, without using the language's float parser.
  • Add thousands separators or hexadecimal literals.
  • Report the position of the first invalid character.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding