8. String to Integer (atoi)

题目如下:

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.

这个题目整体上难度很低,只不过因为每次都少考虑一些特殊情况,导致这道题的AC RATE比较低。

代码就不贴上来了,主要就其中几个特殊情况进行说明一下:

1.+/-符号,需要考虑数字前的+/-号

2.空格及其他字符,从字符串最开始出现的连续空格是允许的,直接无视掉就可以了。数字中出现一些其他字符时,立刻输出当前的数即可。

3.0,出现在数字开头的0

4.溢出情况,对于溢出情况,我采取的方法是,采用double类型来存储结果,然后每一步都进行对于INT的最大最小值2147483647与-2147483648进行判断,如果溢出直接输出最大最小值即可。在最后返回时,对double类型进行类型转换为int即可。

posted on 2016-11-26 15:49  Bismarck  阅读(123)  评论(0)    收藏  举报