題目如下:
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.
解題思路:
首先,要判斷該字符串是否可以還換成int類型,然後,判斷字符的符號(測試集中有-和+),最後將字符傳中的數逐個取出即可。
提交的代碼:
public int myAtoi(String str) {
int p = 0, ret = 0;
while(p < str.length() && Character.isWhitespace(str.charAt(p))) ++p;
if(p == str.length()) return 0;
boolean negFlag = (str.charAt(p) == '-');
if(str.charAt(p) == '+' || str.charAt(p) == '-') ++p;
for(; p<str.length(); ++p) {
if(str.charAt(p) > '9' || str.charAt(p) < '0') {
break;
}else {
int digit = str.charAt(p) - '0';
if(!negFlag && ret > (Integer.MAX_VALUE - digit) /10)
return Integer.MAX_VALUE;
else if(negFlag && ret < (Integer.MIN_VALUE + digit)/10)
return Integer.MIN_VALUE;
ret = ret * 10 + (negFlag? -digit: digit);
}
}
return ret;
}