HardString

Valid Number

LeetCode
1 approach, code in all languages

Given a string, determine whether it represents a valid number. A valid number is an optional sign followed by either an integer or a decimal, optionally followed by an exponent part. A decimal must have digits on at least one side of the dot, an exponent begins with 'e' or 'E' followed by an optional sign and one or more digits, and any leading exponent must be preceded by a valid number.

No surrounding whitespace is allowed and no stray characters are permitted. Your job is to accept only strings that follow these rules and reject everything else.

Example 1

Input: s = "-3.14e2"

Output: true

A leading sign, a decimal part, and a valid exponent together form a well-formed number.

Example 2

Input: s = "1e"

Output: false

The exponent marker 'e' is not followed by any digits, so the string is incomplete.

Constraints

  • 1 ≤ s.length ≤ 20
  • s consists of English letters, digits, and the characters '+', '-', '.'
  • The answer is a single boolean
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now