Leetcode_String To Integer

来源:互联网 发布:ubuntu安装office2013 编辑:程序博客网 时间:2024/05/18 22:50

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.


解题方法:

题目要求实现atoi()函数,难点在于对可能出现的情况判断,最好的办法是同时使用自身的atoi函数和自己写的模拟atoi函数对比,发现atoi()函数有以下特性:

1.对于超过INT_MAX(2147483647) 和小于INT_MIN(-214783648)的值自动返回INT_MAX or INT_MIN

2.小数点之后的全部omit

3.自动跳过字符串开头的空格,first possible character can be + - . or digit 0-9,对于其他一切case,均return 0 

4.若有一个sub string可以组成一个integer,对之后出现的任意非digit符号全部省去,e.g.  "   +344.-245   ",atoi返回 344.之后的 ".-245  "自动省去。

另外需要注意的是,将const char * str 通过 string s(str) 转换成string再使用stl会更方便一些。

INT_MIN 始终,即使乘以1个负数,另外比较tricky的就是bound判断。必须在完成加或者乘之前进行范围判断,否则加乘过后一旦越界,会出现错误的答案。要确保接下来的操作不会越界才能继续接下来的工作。


int atoia(const char *str) {string s(str);size_t begin = s.find_first_not_of(" ");if(begin == string::npos)return 0;s = s.substr(begin, s.size()-begin);size_t end = s.find_first_not_of("0123456789",1);s = s.substr(0,end);if(s.size() ==1 && !isdigit(s[0]))return 0;int sign = 1;if(!isdigit(s[0])){if(s[0] == '+'){}else if(s[0] == '-'){sign = -1;}else return 0;s = s.substr(1,s.size()-1);}string::iterator iter = s.begin();int sum = 0;while(iter != s.end()){if(sign == 1 && INT_MAX - sum < (*iter - '0'))return INT_MAX;if(sign == -1 && INT_MIN + sum > -(*iter - '0'))return INT_MIN;sum += (*iter - '0');++iter;if(iter != s.end()){if(sign == 1 && sum > INT_MAX/10)return INT_MAX;if(sign == -1 && -sum < INT_MIN/10)return INT_MIN;sum*=10;}}if(sign == -1)return -sum;return sum;}


0 0