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.


大致意思:一句话概括就是实现atoi()函数。即实现string转换成int功能。

常规解法:看到这个题目,我第一想法就是通过c++流的方式进行string和int之间的转换,注意空字符串返回0,单独处理即可。一次通过,看到通过率那么低,感觉好神奇。

class Solution {
public:
    int myAtoi(string str) {
        if(str=="")
            return 0;
        stringstream stream(str);
        int a;
        stream>>a;
        return a;
    }
};

看到网上其他解法那么长代码,我就不介绍了,要考虑很多输入细节,大家可以自行查阅。
下面把本题需要注意的地方列出:

  1. 首先需要丢弃字符串前面的空格;

  2. 然后可能有正负号(注意只取一个,如果有多个正负号,那么说这个字符串是无法转换的,返回0。比如测试用例里就有个“+-2”);

  3. 字符串可以包含0~9以外的字符,如果遇到非数字字符,那么只取该字符之前的部分,如“-00123a66”返回为“-123”;

  4. 如果超出int的范围,返回边界值(2147483647或-2147483648)。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容