Valid Number

Medium~15 min

Determine if a given string represents a valid number. A valid number is either an integer or a decimal number, with an optional leading + or - sign.

Valid numbers: "2", "0089", "-0.1", "+3.14", "-.9", "3.", ".5"

Invalid numbers: "abc", "1a", "", ".", "+-3", "1.2.3"

Rules:

  • An optional + or - sign may appear at the start
  • At least one digit must be present (before or after the decimal point)
  • At most one decimal point '.' is allowed
  • No other characters are permitted (no scientific notation, no spaces)

Examples

Example 1
Input: s = "3.14"
Output: true
Explanation: Valid decimal number with digits on both sides of the decimal point.
Example 2
Input: s = "-0.1"
Output: true
Explanation: Negative sign followed by a valid decimal number.
Example 3
Input: s = "abc"
Output: false
Explanation: Contains non-digit, non-sign, non-dot characters.

Constraints

  • 0 <= s.length <= 100
  • s consists of characters: digits (0-9), '.', '+', '-', and letters.
  • No scientific notation (e.g., "1e5" is not considered in this problem).
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run