[LeetCode]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.

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.

我的代码。。。

// StringToInteger.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <string.h>
#include <limits.h>
#include <iostream>
using namespace std;
class Solution {
public:
	int atoi(const char *str) {
		int len = strlen(str);
		if (len == 0)
			return 0;
		int index = 0;
		int flag = 1;
		while (index < len)
		{
			if (str[index] >= '0'&&str[index] <= '9')
			{
				break;
			}
			else if (str[index] == '+')
			{
				flag = 1;
				index++;
				break;
			}
			else if (str[index] == '-')
			{
				flag = -1; 
				index++;
				break;
			}
			else if (str[index] == ' ')
			{
				index++;
			}
			else
			{
				break;
			}

		}
		//cout << index << "pp" << endl;
		if (index == len)
			return 0;
		int sum = 0;
		while (index < len)
		{
			if (str[index] >= '0'&&str[index] <= '9')
			{
				
				if (flag == 1)
				{
					if (sum >INT_MAX/10)
					{
						return INT_MAX;
					}
					if (sum * 10 > INT_MAX - ((str[index] - '0')))
					{
						return INT_MAX;
					}
				}
				else
				{
					if (flag*sum < INT_MIN / 10)
					{
						return INT_MIN;
					}
					if (flag*sum*10 <(INT_MIN - flag*((str[index] - '0'))))
					{
						return INT_MIN;
					}
					
				}
				sum = sum * 10 + (str[index] - '0');
				//cout << sum << endl;
			}else
			break;

			index++;
		}
		return sum*flag;
	}
};
int _tmain(int argc, _TCHAR* argv[])
{
	Solution ss;
	char*s = "-2147483649";
	cout << ss.atoi(s) << endl;
	system("pause");
	return 0;
}

  其中难点是判断溢出这部分,感觉自己实现有点渣。。。

  或者直接用long类型吧,比较简单,直接判断和INT_MAX和INT_MIN大小即可

posted @ 2014-10-20 19:47  supernigel  阅读(122)  评论(0编辑  收藏  举报