首页 > 代码库 > String to Integer (atoi)问题

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.

 

同样是考虑细心程度的题目,贴一下要求吧:

 

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.

 

有了具体的要求,写起来就很简单了。

#include <string.h>int myAtoi(char* str) {    int max=~(unsigned int)0/2;    int min=~max;    int sign=0,num=0,i=0,digits=0;    int len=strlen(str);    if(len==0||len==1&&!(str[i]>=0&&str[i]<=9))        return 0;    while(str[i]== )        i++;    if(i>=len||i==len-1&&!(str[i]>=0&&str[i]<=9))        return 0;    if(str[i]==+||str[i]==-){        sign=(str[i]==+)?0:1;        i++;    }    while(i<len-1&&digits<9){        if(!(str[i]>=0&&str[i]<=9))            return sign?-num:num;        num=num*10+str[i++]-0;        digits++;    }    if(!(str[i]>=0&&str[i]<=9))        return sign?-num:num;    if(str[i+1]>=0&&str[i+1]<=9)        return sign?min:max;    if((num>max/10||(num==max/10&&str[i]-0>max%10))&&!sign)        return max;    else if((-num<min/10||(-num==min/10&&-(str[i]-0)<min%10))&&sign)        return min;    else        num=num*10+str[i]-0;    num=sign?-num:num;    return num;}

我写的对溢出的处理比较烂,聪明的你应该能写出更好的算法来。

String to Integer (atoi)问题