leetcode 练习题 -- 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 aconst 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.

这个题的题目要求估计很多人也没看懂 博主也是实验了五次后才弄懂所有的规则 这里给大家罗列一下

(1)舍弃字符串之前所有的空格 “    206” 返回 206

(2)不能出现多个正负号,有一个判断用例“+-2” 这里出现了多个正负号 返回 0

(3)还有就是正负号出现之后后面必须接着就是数字 例如“ - 3000”负号后有空格 不符合要求 返回 0

(4)字母不能出现在数字前面 像“ -b123456” 这种不符合要求 返回0

(5)只取最前面一段的数字 如“12346bb08”返回值就是 12346



代码如下:

class Solution {
public:
	int myAtoi(string str)
	{
		if (str.length() == 0)return 0;

		char s = '*';                            //记录正负号,随便给一个初始值
		int  flag = 0, sign = 0;                 //flag判断数字串终点 sign判断符号类型
		long long sum = 0;

		for (int i = 0; i < str.length(); i++)
		{

			if (isalpha(str[i]) && flag == 0) return 0;  //字母出现在数字前面,不符合要求

			if (str[i] == '+' || str[i] == '-')
			{
				s = str[i];
				sign++;
				if (!isdigit(str[i + 1])) return 0;       //符号后未接数字 不符合要求
			}
			else if (isdigit(str[i]))
			{
				if (sum > INT_MAX)                       //超出范围退出循环
					break;
				sum = sum * 10 + (str[i] - '0');
				if (flag == 0)
					flag = 1;                      //确定数字已经开始计算
			}
			else if (flag == 1)                            //数字串结束
				break;
		}
		if (s == '+' || sign == 0)                //符号为正或无符号 返回正值
		{
			if (sum>INT_MAX)
				return 	INT_MAX;
			return int(sum);                      //int确保返回值类型符合
		}
		else  
		{
			if (-sum<INT_MIN)
				return INT_MIN;            //INT_MAX和INT_MIN可以直接用
			return int(-sum);
		}
	}
};

猜你喜欢

转载自blog.csdn.net/tobealistenner/article/details/79087084