美文网首页
8. String to Integer (atoi)

8. String to Integer (atoi)

作者: YoungDayo | 来源:发表于2017-09-21 12:22 被阅读0次
字符转整数

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)。

相关文章

网友评论

      本文标题:8. String to Integer (atoi)

      本文链接:https://www.haomeiwen.com/subject/euuzsxtx.html