LeetCode 8. String to Integer (atoi)

来源:互联网 发布:云计算100强 编辑:程序博客网 时间:2024/04/26 03:42

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.

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.

如题所示:

要求实现C++里面的字符串转换成整数的函数atoi,主要需要注意一下几点:

1.开头可能有空格,需要去掉空格符;

2.大小有限制,不能超过INT_MAX也不能小于INT_MIN;

3.如果中途有字符不属于0~9,则输出前面符合条件的结果,如“   -0012a42”,应当输出-12。

代码实现如下:

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


在编写代码的过程中犯了一下几个错误:

1.以为前面都会有正负号,没有考虑到可能没有正负号的情况,直接对index进行index++操作;

2.出现异常字符没有输出前面的数据;

3.超过了INT_MAX的大小,应当输出INT_MAX;

4.由于结果设置的为int类型,因此,当计算后的结果超出了INT_MAX溢出之后,其变成了负数,仍然满足条件小于INT_MAX,因此需要将结果result设置为long类型用于存放数据。

0 0