Valid Number - Problem

Given a string s, return whether s is a valid number.

For example, all the following are valid numbers: "2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789", while the following are not valid numbers: "abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53".

Formally, a valid number is defined using one of the following definitions:

  • An integer number followed by an optional exponent.
  • A decimal number followed by an optional exponent.

An integer number is defined with an optional sign '-' or '+' followed by digits.

A decimal number is defined with an optional sign '-' or '+' followed by one of the following definitions:

  • Digits followed by a dot '.'.
  • Digits followed by a dot '.' followed by digits.
  • A dot '.' followed by digits.

An exponent is defined with an exponent notation 'e' or 'E' followed by an integer number.

The digits are defined as one or more digits.

Input & Output

Example 1 — Valid Scientific Notation
$ Input: s = "3.14e-2"
Output: true
💡 Note: Valid decimal number 3.14 followed by valid exponent e-2, representing 3.14 × 10^(-2) = 0.0314
Example 2 — Invalid Letter Character
$ Input: s = "1a"
Output: false
💡 Note: Contains invalid character 'a' - only digits, signs, decimal point, and e/E are allowed
Example 3 — Valid Decimal Only
$ Input: s = ".5"
Output: true
💡 Note: Valid decimal number - decimal point followed by digits is allowed

Constraints

  • 1 ≤ s.length ≤ 20
  • s consists of only English letters (both uppercase and lowercase), digits (0-9), plus '+', minus '-', or dot '.'.

Visualization

Tap to expand
Valid Number Problem: Input → Validation → OutputInput String"3.14e-2"Validation Process✓ Decimal: 3.14✓ Exponent: e-2ResulttrueValid Components: Sign (optional) + Integer/Decimal + Exponent (optional)✓ Valid: "2", "-0.1", "4.", "2e10"✗ Invalid: "abc", "1a", "1e", "--6"🎯 Key Insight: Use state machine to track valid number component transitions
Understanding the Visualization
1
Input String
String to validate like "3.14e-2"
2
Parse Components
Identify sign, integer, decimal, exponent parts
3
Validation Result
Return true if all components are valid
Key Takeaway
🎯 Key Insight: A valid number follows predictable patterns that can be efficiently validated using a finite state machine
Asked in
Facebook 35 Google 28 Amazon 22
28.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen