题目:
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.
解题思路:1. null or empty string
2. white spaces
3. +/- sign
4. calculate real value
5. handle min & max
代码:
public int atoi(String str) {
double result = 0;
char flag = '+';
int i = 0;
if (str == null || str.length() == 0)
return 0;
str = str.trim();
if (str.charAt(0) == '+') {
flag = '+';
i++;
} else if (str.charAt(0) == '-') {
flag = '-';
i++;
}
while (i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
result = 10 * result + (str.charAt(i) - '0');
i++;
}
if (flag == '-')
result = -result;
if (result > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
else if (result < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
return (int) result;
}