Parse an Integer in Any Base
MicrosoftOnsiteMedium
You implement one function, parse_base_integer(text, base). Each test is a single call. It returns the decimal value of text read in base as a string, or the word INVALID or OVERFLOW when the text or the value is not acceptable.
Part 1: Parse with validation and range check
You are given a string text and an integer base. Read text as an integer written in base and return its decimal value as a string.
Digits are 0 to 9, then a to z for the values 10 to 35, in either upper or lower case. base must be from 2 to 36; any other value returns INVALID. No prefix is recognized or removed: every character of the number is read as an ordinary digit, so 0x1 is three digits in base 36 and invalid in base 16.
First remove ASCII spaces (the space character only) from both ends of text. What remains must be an optional + or - followed by at least one digit that is valid in base. A space anywhere inside, or any other whitespace, is invalid. If the text breaks any of these rules, or base is not from 2 to 36, return INVALID.
If the text is valid but its value is outside the signed 32-bit range, from -2147483648 to 2147483647, return OVERFLOW. Syntax is judged first: a text with a bad character is INVALID even when the digits before it already passed the limit.
Return the value as a decimal string with no leading zeros; zero is 0 whatever its sign. Decide the range while reading the digits; do not rely on a big-integer type.
- Example 1
- base
16- text
"ff"- Output
"255"
Why:
fis 15, soffis 15 * 16 + 15 = 255.
Constraints
0 <= len(text) <= 100-100 <= base <= 100