8. String to Integer (atoi)

原文题目:

8. String to Integer (atoi)

读题:

这个题目主要是判断输入,以及有符号数溢出情况,以下输入是合理的

1) 输入"      12"  输出12

2)输入"     -23a34" 输出-23

3)输入 "+010" 输出10

以下是AC代码:

#define MAXNUM 2147483647
#define MINNUM -2147483648
class Solution 
{
public:
	int myAtoi(string str) 
	{
		int i = 0;
		int result = 0;
		int length = str.size();
		int digit = 0;
		int signal = 1;
		if(!length)
		{
			//cout<<"error! Input is empty!"<<endl;
			return 0;
		}
		while(str[i] ==' ')
		{
			i++;
		}
		if (str[i] =='-')
		{
			signal = -1;
			i++;
		}
		else if(str[i] =='+')
		{
			i++;
		}
		while(i<length)
		{
			if(str[i] <'0'||str[i]>'9')
			{
				return signal*result;
			}
			digit = str[i]-'0';
			if(signal == 1 && result*10.0+digit > MAXNUM)
			{
				return MAXNUM;
			}
			if(signal == -1 && -(result*10.0+digit) < MINNUM)
			{
				return MINNUM;
			}
			result = result*10+digit;
			i++;
		}
		return signal*result;

	}
};

  

原文地址:https://www.cnblogs.com/xqn2017/p/8006426.html