Fork me on GitHub

8. String to Integer (atoi)

8. 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.


解析

这道题要求的 atoi 跟C++实现的不一样吧,比如我以为不符合要求的返回-1,而这道题要求返回0。

所以,有必要解释一下题目的要求:

  1. 首先需要丢弃字符串前面的空格;

  2. 然后可能有正负号(注意只取一个,如果有多个正负号,那么说这个字符串是无法转换的,返回0。比如测试用例里就有个“+-2”);

  3. 字符串可以包含0~9以外的字符,如果遇到非数字字符,那么只取该字符之前的部分,如“-00123a66”返回为“-123”;

  4. 如果超出int的范围,返回边界值(2147483647或-2147483648)。

综上,要求还是有点怪的,不看要求是很难写对的,看了也不一定理解的对。

//8. String to Integer (atoi)
class Solution_8 {
public:
	int atoi1(const char *str) {
		atoi(str);
	}

	int myAtoi(string str) { //int float

		long ret = 0;
		if (str.size() == 0)
		{
			return 0;
		}
		int i = 0;
		while (i < str.size() && isspace(str[i]))
		{
			i++;
		}
		bool flag = false;
		if (i < str.size() && (str[i] == '-' || str[i] == '+'))
		{
			if (str[i] == '-')
				flag = true;
			i++;
		}
		if (str[i] == '+' || str[i] == '-')  //多个正负号,不合法 +-2
		{
			return 0;
		}

		while (i < str.size() && str[i] == '0') //  -0012a42
		{
			i++;
		}
		while (i < str.size())
		{
			if (str[i] >= '0'&&str[i] <= '9')
			{
				ret = ret * 10 + str[i] - '0';

				long temp = flag ? ret*(-1) : ret; //中间结果就判断
				if (temp > INT_MAX)
				{
					return (INT_MAX);
				}
				if (temp < INT_MIN)
				{
					return INT_MIN;
				}

				i++;
			}
			else
			{
				break;  //-0012a42 截断a 
			}

		}
		return flag ? ret*(-1) : ret; // 
	}
};

int atoi(const char *str) {

		long ret = 0;
		int sign = false;
		const char* ptr = str;
		if (ptr==NULL)
		{
			return 0;
		}
		while (isspace(*ptr))
		{
			ptr++;
		}
		if (*ptr == '-' || *ptr == '+')
		{
			if (*ptr=='-')
			{
				sign = true;
			}
			ptr++;
		}

		while (*ptr!='\0'&&(*ptr>='0'&&*ptr<='9'))
		{
			ret = ret * 10 + *ptr - '0';
			long temp=ret*(sign ? -1 : 1);
			if (temp>INT_MAX)
			{
				return INT_MAX;
			}
			if (temp<INT_MIN)
			{
				return INT_MIN;
			}
			ptr++;
		}

		if (*ptr != '\0'&&(*ptr < '0'||*ptr > '9'))
		{
			return ret*(sign ? -1:1);
		}

		return ret*(sign ? -1 : 1);
	}

题目来源

posted @ 2018-01-16 21:49  ranjiewen  阅读(216)  评论(0编辑  收藏  举报