題目
原題頁面:https://leetcode.com/problems/string-to-integer-atoi/
題目型別:Math, String
難度評價:Easy
類似題目:(E) Reverse Integer, (H) Valid Number
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes:
It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.Update (2015-02-10):
The signature of theC++function had been updated. If you still see your function signature accepts aconst char *</code>argument, please click the reload button to reset your code definition.Requirements for atoi:
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. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
分析
- 正負號自然不用說,還要注意字串開頭允許任意長度的空格,結尾允許任意長度的非數字字元。
- int為32位資料型別,當字串代表的整數值超出int的表示範圍時(大於int最大值,或小於int最小值),要能截斷到int的最大值或最小值。但是如何判斷當前的值已經大於int最大值或者小於int最小值,此時如果用int儲存當前值的話,已經發生溢位而出錯。當然,這裡是用Python來解題的,整數變數的範圍不止32位。但是如果是用C++結題呢?一般兩種做法,一個是用更大的資料型別,如long long來儲存當前值。還有一種辦法,就是類似於下面的程式碼中的方法,就是直接用當前值的字串,和int最大值最小值的字串去進行字串大小比較。
程式碼
1 | class Solution: |
本文地址:https://xnerv.wang/zh-tw/leetcode-string-to-integer-atoi/
