1. valid char c : c - '0',
2.not valid char: stop3.'+'or'-' sign atthestart, record it4. Overflow: INT_MAX (2147483647) or INT_MIN (-2147483648) is returned
publicclass{ publicintatoi(String str){ if (str == null || str.length() == 0) return0; int sign = 1; int index = 0;
// if we use long, we should return MAX or MIN value directly, double num = 0;
str = str.trim();
if (str.charAt(index) == '+') index++; elseif (str.charAt(index) == '-'){ sign = -1; index++; } for (; index < str.length(); index++){ char current = str.charAt(index); if (current > '9' || current < '0' || num > Integer.MAX_VALUE) break; num = num * 10 + (current - '0'); }
return (int) (sign * num); }
// If double and long are not allowed publicintatoi(String str){ if (str == null || str.length() == 0) return0; int sign = 1; int index = 0; int num = 0; str = str.trim();
if (str.charAt(index) == '+') index++; elseif (str.charAt(index) == '-'){ sign = -1; index++; } for (; index < str.length(); index++){ char current = str.charAt(index); if (current > '9' || current < '0') break; if (num > Integer.MAX_VALUE / 10 || (num == Integer.MAX_VALUE / 10 && num > Integer.MAX_VALUE % 10)) return sign > 0? Integer.MAX_VALUE : Integer.MIN_VALUE; num = num * 10 + (current - '0'); }
近期评论