讨论/《图解算法数据结构》 - 剑指 Offer 67. 把字符串转换成整数/
《图解算法数据结构》 - 剑指 Offer 67. 把字符串转换成整数

C++ 简单易懂

class Solution {
public:
	int strToInt(string str)
	{
		string ss;
		int flag = 1;
		int bndry = INT_MAX / 10;
		int num = 0;
		//erase space 
		for (size_t i = 0; i < str.size(); ++i)
		{
			if (str[i] == ' ') continue;
			ss = str.substr(i, str.size() - i);
			break;
		}
		if (ss.empty()) return 0;
		else if (ss[0] == '+' || ss[0] == '-' || ss[0] >= '0' && ss[0] <= '9')
		{
			if (ss[0] == '-') flag = -1;
			if (ss[0] == '+' || ss[0] == '-')
			{
				for (size_t i = 1; i < ss.size(); ++i)
				{
					if (ss[i] < '0' || ss[i] > '9') break;
					if (num > bndry || (num == bndry && ss[i] > '7'))
					{
						return 1 == flag ? INT_MAX : INT_MIN;
					}
					num = 10 * num + (ss[i] - 48);
				}
			} 
			else if(ss[0] >= '0' && ss[0] <= '9')
			{
				for (size_t i = 0; i < ss.size(); ++i)
				{
					if (ss[i] < '0' || ss[i] > '9') break;
					if (num > bndry || (num == bndry && ss[i] > '7'))
					{
						return INT_MAX;
					}
					num = 10 * num + (ss[i] - 48);
				}
			}
		}
		else
		{
			return 0;
		}
		return flag * num;
	}
};
1
展开全部 9 讨论