leetcode-8. String to Integer (atoi)

Posted perfy576

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-8. String to Integer (atoi)相关的知识,希望对你有一定的参考价值。

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)的主要内容,如果未能解决你的问题,请参考以下文章

8. 字符串转整数(实现atoi函数) [leetcode 8: String to Integer (atoi)]

leetcode-8. String to Integer (atoi)

Leetcode 8. String to Integer (atoi)

[LeetCode] 8. String to Integer (atoi) ☆

LeetCode 8. String to Integer (atoi)

Leetcode:8- String to Integer (atoi)