leetcode[8]:String to Integer (atoi)

来源:互联网 发布:新网域名转出申请书 编辑:程序博客网 时间:2024/06/06 02:16

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.

int myAtoi(char* str) {    int i;    int flag=0;    unsigned int res=0;    int p,lag=0;    if(str[0]==0) return 0;    for(i=0;str[i]!='\0';i++)    {        if(((str[i]<48 && str[i]!=45 && str[i]!=43) || str[i]>57 ) && str[i]!=' ') break;        if(str[i]==45)  if(flag==0) {flag=1;lag=1; continue;}                    else return 0;        if(str[i]==43)  if(flag==0) {flag=2;lag=1; continue;}            else return 0;        if(str[i]==' ')if(lag==0) continue;        else if(lag) break;        res=res*10+str[i]-48;         if(res>=214748364) break;        lag=1;    }    if(res>=214748364 &&  str[i+1]>='0' && str[i+1]<='9')         if(res==214748364 && str[++i]<='8' &&  (str[i+1]<'0' || str[i+1]>'9'))         res=res*10+str[i]-48;        else res=2147483648;    if(flag==1 && res > 2147483648) return -2147483648;    if(flag!=1 && res>2147483647) return 2147483647;    p=res;    if(flag==1) p=-p;    return p;}

1.前置空格接受。
2.数字首部唯一的正负号接受。
3.数字中间出现任何非数字(空格,字母,符号等)视为数字结束。
4.数字越界问题——INT_MAX (2147483647) or INT_MIN (-2147483648) 。
5.字符数组为空。

0 0