題目如下:
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.
這道題簡單是挺簡單的,關鍵是你要考慮到它的各種情況,比如越界,空格等等情況,我試了好久才搞定。。。刷的快吐了
public class Solution {
public int myAtoi(String str) {
long result = 0;
boolean flag = false;
int i = 0;
while (i < str.length() && str.charAt(i) == ' ')
i++;
if (i < str.length() && str.charAt(i) == '-') {
flag = true;
i++;
}else if (i < str.length() && str.charAt(i) == '+') {
i++;
}
while (i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
result = result * 10 + str.charAt(i) - '0';
if((flag && result<Integer.MIN_VALUE) || result>Integer.MAX_VALUE) break;
i++;
}
if (flag) {
result = result * -1;
if (result < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
else {
return (int) result;
}
} else {
if (result > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
else {
return (int) result;
}
}
}
}