String to Integer (atoi)
Thoughts
Code
class Solution {
public int myAtoi(String str) {
int res = 0, sign = 1;
// Empty String
if (str == null || str.length() == 0) {
return res;
}
int i = 0;
// RM white spaces
while (str.charAt(i) == ' ') {
i++;
}
// Handle signs
if (str.charAt(i) == '+' || str.charAt(i) == '-') {
sign = str.charAt(i) == '+' ? 1 : -1;
i++;
}
// Convert number and avoid overflow
for (; i < str.length(); i++) {
int digit = str.charAt(i) - '0';
if (digit >= 0 && digit <= 9) {
if (Integer.MAX_VALUE / 10 < res || Integer.MAX_VALUE / 10 == res && Integer.MAX_VALUE % 10 < digit) {
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
res = res * 10 + digit;
//System.out.println(res + ", " + (res - digit) / 10);
} else {
break;
}
}
return res * sign;
}
}Analysis
Last updated