问题描述

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.

问题分析

题目看似简单,但实际上却很麻烦,因为它有很多种情况。下面是我一次又一次去提交然后错误得出来的规则:

  • 有正负号,"-10""+10"是符合规则的,"+-10"是不符合规则的
  • 不符合规则的返回0
  • 越界的根据符号返回-21474836482147483647
  • 需要去掉前面的空格,中间的不能去掉,有这样的用例," -100"是符合规则的;" +0 10"是不符合规则的
  • 如果字符串中有字母,字母及其后面的舍去,如"-10a100",返回-10

代码

class Solution {
public:

    int myAtoi(string str) {
		if(str == "") {
			return 0;
		}
		// 去掉前面的空格
		string::size_type pos = 0;
		while((pos=str.find(" ", pos))!=string::npos) {
			if(pos!=0) {
				break;
			}
			str.erase(pos, 1);
			pos = 0;
		}
		 
		int r = 0;
		// 检测是否合法
		if(str.size()==1) {
			if(str[0] >= '0' && str[0] <= '9') {
				return str[0] - '0';
			} else {
				return 0;
			}
		}
		if(str[0]=='+'||str[0]=='-') {
			if(str[1]<'0'||str[1]>'9') {
				return 0;
			}
		}
		for(int i=0;i<str.size();i++) {
			char ch = str[i];
			if(ch>='0' && ch<='9') {
				int tmp = r*10 + int(ch - '0');
				// 检测溢出 
				if((tmp/10!=0&&((tmp - int(ch - '0'))/10!=r))||(tmp>0&&r<0)||(tmp<0&&r>0)) {
					r = str[0]=='-'?-2147483648:2147483647;
					break;
				}
				cout<<tmp<<endl;
				r = tmp;
			} else if(ch!='-' && ch!='+') {
				return str[0]=='-'?-r:r;
			}
		}
		return str[0]=='-'?-r:r;   
    };
};

写的很乱,实在是有些被逼疯了。。。