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 a const char * argument, please click the reload button  to reset your code definition.

分析:

题目理解就废了一番功夫,看了几遍也没有抓住精髓。
该题目是说将string类型的字符串转换成整型数据,类似于C++库里的atoi函数,解决该题目的关键在于两个方面:
(1)字符串格式的合法判断
(2)转换结果的溢出判断
首先,对于字符串格式,空格不计入计算,应从第一个非空字符开始判断,首字母只能是符号(+、-)与数字的一种;从计算开始遍历字符串,到最后一位数字为止;
其次,对于转换结果,我们知道整型数据的范围是INT_MIN(-2147482648)到INT_MAX(2147483647),超出范围则返回最大与最小值。所以我们可以开始用long long类型的变量存储结果;

AC代码:

class Solution {
public:
    int myAtoi(string str) {

		if(str.length() == 0)
			return 0;
		//用于存储结果
		long long result = 0 ;
		int sign = 1 , i=0;

		while(str[i] == ' ')
		{
			if (str[i] == ' ')
				i++;
		}

		if(str[i] == '+')
			i++;
		else if(str[i] == '-')
		{
			sign = -1;
			i++;
		}
		
		for(int j=i ; j<str.length() ; j++)
		{
			if(str[j]>='0' && str[j]<='9')
			{
				result = result * 10 + (str[j]-'0');
				if(result > INT_MAX)
					return sign<0 ? INT_MIN : INT_MAX;
			}
			else
				break;
		}
		result *= sign;
		return (int)result;
    }
};


原文地址:https://www.cnblogs.com/shine-yr/p/5214960.html