Check Whether a Token Is a Well-Formed Decimal Literal
StringsAuto-graded · 41 test casesLast updated
Scan a string once to decide if it matches a small decimal-literal grammar with optional sign, a dotted mantissa and an optional exponent, handling many edge cases.
Decimal Literal Checker
You are given a string token made of ASCII characters. Decide whether it is a well-formed decimal literal according to the rules below, and return True if it is and False otherwise.
Format
A literal has up to three parts, written in this order:
- Sign (optional). A single
+or-at the very start. - Mantissa (required). A run of decimal digits that may contain at most one decimal point
., which can be at the start, in the middle, or at the end of the run. The mantissa must contain at least one digit. A lone.is therefore not a mantissa. - Exponent (optional). The letter
eorE, then an optional+or-, then one or more digits. The exponent part is an integer only, so it cannot contain a decimal point.
Additional rules
- The whole string must match the format. No spaces, commas, underscores, letters other than the exponent marker, or any other characters are allowed anywhere.
- Leading zeros are fine.
- Only one sign may appear before the mantissa, and only one decimal point may appear in the mantissa.
- Only digits
0through9count as digits. - The empty string is not valid.
For example, strings such as e3, +., 1.2.3, --6, 6e and 6e- are all invalid.
Task
Implement the function so that it returns True exactly when token is a well-formed decimal literal under these rules.
Constraints
0 <= len(token) <= 10^5tokenconsists of ASCII characters.- Do not rely on
float()conversion to decide validity. - Aim for linear time and constant extra space.
Examples
Example 1
Input: is_decimal_literal('123')
Output: True
Example 2
Input: is_decimal_literal('0.5')
Output: True
Example 3
Input: is_decimal_literal('.8')
Output: True
Example 4
Input: is_decimal_literal('10.')
Output: True
Example 5
Input: is_decimal_literal('1e9')
Output: True
Example 6
Input: is_decimal_literal('-3.2E-4')
Output: True
Example 7
Input: is_decimal_literal('e3')
Output: False
Example 8
Input: is_decimal_literal('+.')
Output: False
Example 9
Input: is_decimal_literal('1.2.3')
Output: False
Example 10
Input: is_decimal_literal('--6')
Output: False
Example 11
Input: is_decimal_literal('6e')
Output: False
Example 12
Input: is_decimal_literal('6e-')
Output: False
Hints
Hint 1
The format has no nesting, so a single left-to-right pass with one moving index is enough. Handle the parts in order: sign, mantissa, exponent.
Hint 2
In the mantissa, count digits and remember whether a dot was already seen. After the loop, require at least one digit. This one check rejects '.', '+.', '-' and 'e3'.
Hint 3
After an optional exponent marker and optional sign, require at least one exponent digit. At the end, return whether the index reached the end of the string, which catches any leftover characters such as a second dot or sign.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The format is a small fixed grammar with no nesting:
literal := [sign] mantissa [exponent]
mantissa := digits with at most one '.', at least one digit
exponent := ('e' | 'E') [sign] digit+
So a single left-to-right scan with one index i is enough. The scan moves through phases in order:
- Sign. If the first character is
+or-, skip it. - Mantissa. Advance over digits and at most one
., counting digits. Stop at the first character that does not fit (a second dot, ane/E, or any other character). - Mantissa check. If no digits were counted, return
False. This covers"","+",".","+."and"e3". - Exponent. If the current character is
eorE, skip it, skip an optional sign, then count digits. If there are none, returnFalse. This covers"6e"and"6e-". - Full consumption. Return
i == n. Any leftover character, such as a second dot, a second sign, a dot in the exponent, or whitespace, makes the string invalid.
Why it is correct
- The sign is only examined at position 0 (and right after the exponent marker), so a second sign such as in
--6stops the mantissa loop with zero digits and fails. - Counting digits, rather than tracking where the dot sits, handles
.8,10.and0.5as valid while rejecting.and+.. - A second dot ends the mantissa loop early, so
i < nand the final check fails. - The exponent has its own digit counter, so
6eand6e-are rejected, and a dot aftereis never consumed, so it fails the final check. - Digits are compared with
"0" <= c <= "9", so only ASCII digits are accepted, and leading zeros are fine because digit values are never examined. - Every character is either consumed by a rule that allows it or left behind, and leftovers are caught by
i == n. The scanner therefore accepts exactly the strings the grammar describes.
Complexity
- Time: O(n), since the index only moves forward.
- Space: O(1), using only a few counters and a flag.
Reference solution
def is_decimal_literal(token: str) -> bool:
n = len(token)
if n == 0:
return False
i = 0
if token[i] in "+-":
i += 1
mantissa_digits = 0
saw_dot = False
while i < n:
c = token[i]
if "0" <= c <= "9":
mantissa_digits += 1
i += 1
elif c == "." and not saw_dot:
saw_dot = True
i += 1
else:
break
if mantissa_digits == 0:
return False
if i < n and token[i] in "eE":
i += 1
if i < n and token[i] in "+-":
i += 1
exponent_digits = 0
while i < n and "0" <= token[i] <= "9":
exponent_digits += 1
i += 1
if exponent_digits == 0:
return False
return i == n