[LeetCode]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.

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.

思考:根据提示考虑3点:空格,+-,溢出。

        看了下atoi源码,果然我写的是一坨屎。不过atoi没有考虑溢出。

class Solution {

public:

    int atoi(const char *str) {

        // IMstrORTANT: strlease reset any member data you declared, as

        // the same Solution instance will be reused for each test case.

      //  if(str[0]=='\0') return 0;

		if(str==NULL) return 0;

		bool flag=false;

		int ret=0;

		int i=0;

		while(str[i]==' ') i++;

		if(str[i]=='+'||str[i]=='-')

		{

			flag=(str[i]!='+');

			i++;

		}

		for(;str[i]!='\0';i++)

		{ 

			if(str[i]>='0'&&str[i]<='9')

			{

				if(INT_MAX/10>=ret&&(INT_MAX-(str[i]-'0')>=ret*10))

					ret=ret*10+(str[i]-'0');

				else return flag?INT_MIN:INT_MAX;				

			}

			else break;

		}

		return flag?0-ret:ret; 

	}

};

2014-03-14 11:54:06

class Solution {

public:

    int atoi(const char *str) {

		assert(str!=NULL); //空指针

		while(*str==' ') str++;

//		if(*str=='\0') return 0; //空格

		int res=0; //返回值

		bool flag=true; //正负

		if(*str=='+') str++;

		if(*str=='-') 

		{

			str++;

			flag=false;

		}

		while(*str!='\0')

		{	

		    //"  -0012a42"返回-12而不是0;

		    if(!isdigit(*str)) return flag?res:(0-res);

		    //if(INT_MAX-(*str-'0')<res*10) 错!res*10会越界

			if((INT_MAX-(*str-'0'))/10<res) //判断是否越界

				return flag?INT_MAX:INT_MIN;

			res=res*10+(*str-'0');

			str++;

		}

		return flag?res:(0-res);

    }

};

  

 

你可能感兴趣的:(LeetCode)