Leetcode 8. String to Integer (atoi)

来源:互联网 发布:super() python 编辑:程序博客网 时间:2024/06/16 21:06

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.

算法思想:一共有以下注意点:

1.空串直接返回0;

2.要舍去前面的空格

3.舍去空格后第一字符若不是‘+’,'-',或数字,返回0

4.计算从第一数字的位置开始,到字符串末尾或者到非数字字符结束

5.溢出处理:如果超出int的最大值,则输出最大值。若比最小值还小,则直接输出最小值。(利用较大的类型存储,最后在强制转换)

代码如下:

class Solution {public:    int myAtoi(string str) {        if(str.size()==0)//空串            return 0;                        int start,flag;//数值开始位置,正负标志        for(start=0;start<str.size();start++)//舍去前面的空格            if(str[start]!=' ')                break;        if(start==str.size())//由空格组成的字符串            return 0;                    if(str[start]=='+'){            start++;            flag=1;        }        else if(str[start]=='-'){            start++;            flag=-1;        }        else if(isdigit(str[start])){            flag=1;        }        else            return 0;//第一的字符不是数字或加减号                        long long ans=0;            for(int i=start;(i<str.size())&&isdigit(str[i]);i++){            ans=ans*10+flag*(str[i]-'0');            if(ans>INT_MAX)//溢出处理                return INT_MAX;            else if(ans<INT_MIN)                return INT_MIN;        }        return ans;    }};


0 0
原创粉丝点击