Valid Number
Real-world version: Reading Token ValidatorThe statement here is our own: the same inputs, outputs and technique.
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.
def is_valid_reading(token: str) -> bool:public boolean isValidReading(String token)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 20 test cases: 20 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's