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

题目大意:该题目是说将string类型的字符串转换成整型数据,类似于C++库里的atoi函数,解决该题目的关键在于两个方面:

(1)字符串格式的合法判断

(2)转换结果的溢出判断

首先,对于字符串格式,空格不计入计算,应从第一个非空字符开始判断,首字母只能是符号(+、-)与数字的一种;从计算开始遍历字符串,到最后一位数字为止;

其次,对于转换结果,我们知道整型数据的范围是INT_MIN(-2147482648)到INT_MAX(2147483647),超出范围则返回最大与最小值。所以我们可以开始用long long类型的变量存储结果;


代码如下:

class Solution {
public:
    int myAtoi(string str) {
    	if (str.empty())
    		return 0;
    	int flag = 1;//flag 1正 -1负
    	long long result = 0;
    
    	int i = 0;
    	while (str[i] == ' ')
    	{
    		i++;
    	}
    
    	if (str[i] == '-')
    	{
    		i++;
    		flag = -1;
    
    	}
    	else if (str[i] == '+')
    	{
    		i++;
    	}
    
    	for (int j = i; j < str.length(); j++)
    	{
    		if (str[j] >= '0' && str[j] <= '9')
    		{
    			result = result * 10 + (str.at(j) - '0');
    			if (result > 2147483647)
    			{
    				if (flag == 1)
    					result = INT_MAX;
    				else
    				{
    					result = INT_MIN;
    					flag = 1;
    				}
    				break;
    			}
    		}
    		else
    			break;
    	}
    	return flag * result;
    }
};


2016-08-09 00:18:49