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) {
if (str == null || str.length() == 0)
return 0;
int i = 0, pow = 0, sign = 1;
long res = 0;
while (str.charAt(i) == ' ')
i++;
if (str.charAt(i) == '-') {
sign = -1;
i++;
}
else if (str.charAt(i) == '+') {
i++;
}
for (; i < str.length(); i++) {
if (str.charAt(i) < '0' || str.charAt(i) > '9')
return (int) res * sign;
else {
res = res * 10 + (str.charAt(i) - '0');
if (res * sign < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
else if (res * sign > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
}
}
return (int) res * sign;
}
}