8String to Integer (atoi)

来源:互联网 发布:dnf安徒恩优化补丁 编辑:程序博客网 时间:2024/06/12 21:09

8 String to Integer (atoi)

链接:https://leetcode.com/problems/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.

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.

Hide Tags Math String

将字符串转换为int,需注意:
1 字符串开头的空格需要去掉;
2 字符串开头出了符号(‘+’,‘-’),一定要以数字开始,否则返回0;
3 在转换的过程中,如果出现非数字的情况则转换立即终止;
4 注意溢出的问题,如果数字大于INT_MAX返回INT_MAX,如果小于INT_MIN则返回INT_MIN。

class Solution {public:    int myAtoi(string str) {        if(str=="")            return 0;        str=str.substr(str.find_first_not_of(" "));        bool flag=true;        for(int i=0;i<str.size();i++)        {         if(str[i]-'0'<10&&str[i]-'0'>-1)         {            if(i>1)                return 0;            else if(i==1)            {                if(str[0]=='-')                    flag= false;                else if(str[0]!='+')                    return 0;                str=str.substr(1);                break;            }            break;         }        }        long long int result=0;        for(int i=0;i<str.length();i++)        {            if(str[i]-'0'<10&&str[i]-'0'>-1)            {             result=result*10+str[i]-'0';                if(result>INT_MAX)                {                   if(!flag)                       return INT_MIN;                   else                       return INT_MAX;                          }            }            else                break;        }        if(!flag)            result=-result;        return result;    }};
0 0