1. 程式人生 > >LeetCode 8. String to Integer (atoi)

LeetCode 8. String to Integer (atoi)

req argument require git empty convert int oss 非法字符

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 the C++ function had been updated. If you still see your function signature accepts a const char * 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.

這道題說的已經很清楚了,要求實現atoi這樣一個函數,標準庫中關於這個函數有詳細介紹http://www.cplusplus.com/reference/cstdlib/atoi/?kw=atoi

根據題目中的描述,我們需要做以下幾件事情:

  1. 先跳過一開始的空格字符串
  2. 進行符號的判決,如果一開始讀到的字符就是非法字符,直接返回0
  3. 開始讀取數字,如果讀到非法字符,直接輸出當前數字,這個過程中註意處理溢出,如果超過最大值,返回INT_MAX,小於最小值,返回INT_MIN;
  4. 最後把基數與符號相乘,返回結果

代碼如下:(寫的時候註意,有幾個地方涉及到字符串的比較,比如 str[i] - ‘0‘ > 7 不要寫成str[i] > 7)

 1 class Solution {
 2 public:
 3     int myAtoi(string str)
 4     { 
 5        int sign = 1, base = 0, i = 0, len = str.size();
 6         while (i < len && str[i] ==  )
 7             i++;
 8         if(str[i] == + || str[i] == -)
 9             sign = (str[i++] == + )? 1:-1;
10         while (i < len && str[i] >= 0 && str[i] <= 9)
11         {
12             if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - 0 > 7))
13             {
14                 if (sign == 1)
15                     return INT_MAX;
16                 else 
17                     return INT_MIN;
18             }
19              base = base * 10 + (str[i++] - 0);   
20         }
21         return base * sign;
22     }
23 };

LeetCode 8. String to Integer (atoi)