Strict Text to Integer for a Given Size
Problem statement
Convert the text s into a signed integer of size bits, whose values run from -2^(bits-1) to 2^(bits-1) - 1 (for 16 bits: -32768 to 32767; for 32 bits: -2147483648 to 2147483647).
- Spaces at the start and end are ignored; no other character is trimmed.
- What is left is valid only if it is one or more digits, optionally after a single leading
-. Leading zeros are fine. - If the text is not valid, or its value does not fit the size, return the largest value of the size,
2^(bits-1) - 1.
Otherwise return the value. Your code should work for either size, without assuming how big an integer is.
Function
parseStrict(s: String, bits: int) → intExamples
Example 1
s = " -2048 "bits = 16return = -2048The spaces around the text are ignored. -2048 is a minus sign followed by digits, and it fits in 16 bits (from -32768 to 32767), so the answer is -2048.
Example 2
s = "40000"bits = 16return = 3276740000 is above 32767, the largest 16-bit value, so the answer is 32767. With bits = 32 the same text would give 40000.
Example 3
s = "12 34"bits = 32return = 2147483647A space inside the number makes it invalid, so the answer is the largest 32-bit value, 2147483647.
Constraints
0 <= s.length <= 200scontains printable ASCII characters only (codes 32 to 126)bitsis16or32