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

leetcode-8. String to Integer (atoi)

then ble sig 記得 repr exist elf sta eric

1 題目

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.

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.

2 分析

隱約的記得在劍指offer上做過一次了。

主要是分析

  1. - + 只能出現在第一個位置和e的後面。且不能是最後一位。
  2. e和.只能出現一次。

不過這裏的題簡單的多。

只需要能夠從字符串中提取出數字即可。

因此也就是說只需要:

跳過前導的空格,判斷第一個字符是否是正負號,並記錄正負。

然後判斷後面的字符是否是數字,如果不是數字直接跳過。如果是數字,那麽合成數字,並且判斷是否越界。

最後判斷是否只有一個正負號

返回

leetcode-8. String to Integer (atoi)