LeetCode: 8-String to Integer (atoi) 解題紀錄
Last Updated on 2022-01-14 by Clay
題目
Implement atoi which converts a string to an integer.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned.
Note:
Only the space character ' ' is considered a whitespace character.
Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. If the numerical value is out of the range of representable values, 2^31 − 1 or −2^31 is returned.
Example:
Input: str = "42"
Output: 42
Input: str = " -42"
Output: -42
Input: str = "4193 with words"
Output: 4193
Input: str = "words and 987"
Output: 0
Input: str = "-91283472332"
Output: -2147483648
本題要實作 atoi() 這一函式,也即是題目給定一組字串輸入,我們要將其可能轉換成整數字串部分提取出來並回傳該整數。
- 若是字串先碰到文字,則回傳 0
- 若是該整數 > 2^31 -1 或整數 < -2^31,則回傳整數型態限制的最大值或最小值