Show problems as
Classic problem #65HardString

Valid Number

Real-world version: Reading Token Validator
Tracked in this browser only
Read Valid Number on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstRegular Expressions · Strings, animated step by step

A field logger writes one token per line and you are asked to sieve out the malformed ones. A token is a valid reading exactly when it can be cut into a body, optionally followed by a scale part, with nothing left over.

A body is an optional single + or -, followed by one of these three shapes:

  • one or more digits;
  • one or more digits, then ., then zero or more digits;
  • ., then one or more digits.

A scale part is the letter e or E, then an optional single + or -, then one or more digits.

Any other letter, a second ., a second e or E, a sign that is neither at the very start nor directly after e or E, or a . sitting inside the scale part all make the token invalid. Decide it by inspecting the characters; do not hand the token to a built-in numeric conversion.

Given token, return true when it is a valid reading and false otherwise.

Examples

Example 1

Input
token = "+3e-2"
Output
true

The body is +3, which is a sign followed by one digit, and the scale part is e-2, which is the marker, a sign and one digit.

Example 2

Input
token = "46.e3"
Output
true

The body 46. is digits followed by a dot with no digits after it, which the second shape allows, and e3 is a well-formed scale part.

Example 3

Input
token = "2e4.1"
Output
false

The dot falls inside the scale part, where only a sign and digits may appear.

Constraints

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

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def is_valid_reading(token: str) -> bool:
Java
public boolean isValidReading(String token)