LeetCode 8 String to Integer (atoi)

来源:互联网 发布:sql select 临时表 编辑:程序博客网 时间:2024/06/14 21:03

8. String to Integer (atoi)

My Submissions
Total Accepted: 95952 Total Submissions: 713471 Difficulty: Easy

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.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.

spoilers alert... click to show requirements for atoi.

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems
Have you met this question in a real interview? 
Yes
 
No

Discuss


实现atoi函数

字符串转整数.

需要注意一下几点

1. 字串为空或者全是空格,返回0; 

2. 字串的前缀空格需要忽略掉;

3. 忽略掉前缀空格后,遇到的第一个字符,如果是‘+’或‘-’号,继续往后读;如果是数字,则开始处理数字;如果不是前面的2种,返回0;

4. 处理数字的过程中,如果之后的字符非数字,就停止转换,返回当前值;

5. 在上述处理过程中,如果转换出的值超出了int型的范围,就返回int的最大值或最小值。


class Solution {public:    int myAtoi(string str)    {        long long ret=0;        int len=str.length();        if(len==1&&str[0]>='0'&&str[0]<='9')                return str[0]-'0';        int pos=0;        while(pos<len&&str[pos]==' '){pos++;}        if(pos==len)                return 0;        int flag=1;        if(str[pos]=='+')                flag=1;        else if(str[pos]=='-')                flag=-1;        else if(str[pos]>'9'||str[pos]<'0')                flag=0;        else            pos--;        for(int i=pos+1;i<len&&str[i]>='0'&&str[i]<='9';i++)        {                ret=10*ret+(str[i]-'0');                if(ret*flag>=INT_MAX)                {                        ret=INT_MAX;                        break;                }                if(ret*flag<=INT_MIN)                {                        ret=INT_MIN;                        break;                }        }        ret*=flag;        return (int)ret;    }};




0 0
原创粉丝点击