id8:String to Integer (atoi) QuestionEditorial Solution My Submissions
Total Accepted: 136242
Total Submissions: 989232
Difficulty: Easy
Contributors: Admin
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.
Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.
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.
这道题目正常的转换非常简单,比较麻烦的就是处理边界问题,在测试集里面需要考虑如下集中边界问题:
- 起始和结束空格问题如
"."
return 0;和"....-48755...."
return -48755, 其中"."
表示空格, - 去掉问题1后的符号字符问题,比如
+8975
return 8975,89454
return 89484,-8975
return -8975, 即必须提取出合适的正负号.其中正号可以省略。 - 去掉1和2问题后的结束字符问题,如,
8986jhuuh
return 8986. 溢出问题,写此文章时2016/11/21,leetcode已经在此测试集中加入了对long long的溢出判断。所以不能使用long long 类型进行溢出判断。可以使用
http://deepdim.com/2016/11/21/Reverse-Integer-%E9%80%86%E7%BD%AEint%E6%95%B0/#more
中的溢出方法,即:使用前一个结果得标志
在溢出得时候只有每次乘以10的时候会产生溢出,假设没乘以10之前的结果保存在pre_result,在乘以10之后的结果为 result,可以使用result/10!=pre_result
来进行溢出判断,因为如果溢出结果就是一个溢出的数字不满足乘以10的结果note: 测试集中存在测试字符串
+-8968
,在去掉1和2问题之后变为’-8968’等同于"."
,所以return 0,如果不好理解,可以将问题放大:如-895-775
在去掉问题1和2的影响后,等同于895
所以return 895.
程序代码如下:
本地测试用例: