← 返回 netflix 的题目列表Parse String to Integer Without Built-ins
类型:online_judge
Problem: Parse String to Integer (No Built-ins)
Implement a function to parse a string into a 32-bit signed integer, and you must not use built-in conversion utilities (e.g., valueOf / parseInt / stoi).
Input
A string s.
Output
Return the integer value if s is a valid integer representation.
Otherwise, throw an exception (or report an error in your implementation).
Validity Rules
Sign:
'-' is allowed to denote a negative number; '+' is not allowed.
If '-' appears, it must be the first character. If '-' appears elsewhere, it is invalid.
Character set:
Other than an optional leading '-', all remaining characters must be digits '0'..'9'.
Any other character (letters or any special characters) makes the input invalid.
Leading zeros:
Exactly one leading zero is allowed.
If the digit part starts with 0 and has length > 1 (e.g., "00", "012", "-01"), it is invalid.
Overflow:
If the parsed value is outside the 32-bit signed integer range [-2^31, 2^31-1], it is invalid and you must throw an exception.
Constraints
1 <= len(s) <= 1e5
Examples
Input: "6" Output: 6
Input: "-6" Output: -6
Input: "012" Output: exception (multiple-digit leading zero)
Input: "12a" Output: exception (contains a letter)
Input: "1-2" Output: exception (- not at the first position)
Input: "2147483648" Output: exception (overflow)
Example
Input
6
Output
6