题目连接:https://leetcode.com/problems/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.
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.
1)输入为空
2)边界问题
3)特殊符号
含泪贴上自己AC的低质量代码,讨论区也有很多人直接用写好的API,或者考虑边界时候使用long类型,还有使用python的正则表达式都有。
public static int myAtoi(String str) {
int res = 0;
// whether res is positive or not
boolean positive = true;
// the num of char before digit
int sigCount = 0;
// ignore the space before or afer the string
String fixStr = str.trim();
if(!fixStr.isEmpty()) {
int len = fixStr.length();
int idx;
// judge the res is positive or not, and if the char before res is not '+' nor '-', return 0
for(idx = 0; idx < len; idx++) {
char ch = fixStr.charAt(idx);
if(ch >= '0' && ch <= '9') {
// begin with digits
break;
} else {
// too many sign or char isn't '+' or '-', e.g. '++-2133', ' b23351'
if(++sigCount > 1 || (ch!='+' && ch!='-'))
return 0;
else if(ch == '-')
positive = false;
}
}
for(; idx < len; idx++) {
char ch = fixStr.charAt(idx);
if(ch >= '0' && ch <= '9') {
// equalsTo "res*10+(ch-'0') > Integer.MAX_VALUE", which is overflow
if(positive && res > (Integer.MAX_VALUE - (ch-'0'))/10)
return Integer.MAX_VALUE;
// equalsTo "-(res*10+(ch-'0')) < Integer.MIN_VALUE", which is overflow
else if(!positive && res > -((Integer.MIN_VALUE + (ch-'0'))/10))
return Integer.MIN_VALUE;
else
res = res*10 + (ch - '0');
} else
// if the test case is '233f54' for example, output will be '233'
break;
}
}
return positive?res:-res;
}