題目連接: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;
}