Solution to LeetCode String to Integer atoi problem.
This is also an implementation question. The one interesting part is how to check for overflow/underflow.
public int atoi(String str) {
char[] C = str.toCharArray();
int N = C.length;
int i = 0;
int neg = 1;
while(i < N && C[i] == ' ') i++; // we are at first nonspace char
if(i == N) return 0; // out of characters
if(C[i] == '+') i++;
else if(C[i] == '-'){
neg = -1;
i++;
}
if(i == N) return 0; // out of chars
if(C[i] < '0' && C[i] > '9') return 0; // wrong first character
// C[i] is now the beginning of the number
int result = 0;
// Check for overflows and return the appropriate limit
while(i < N && C[i] <= '9' && C[i] >= '0'){
int digit = C[i] - '0';
if(result > Integer.MAX_VALUE/10) return (neg > 0) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
result = 10*result;
if(result > Integer.MAX_VALUE-digit) return (neg > 0) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
result += digit;
i++;
}
return neg*result;
}