| 10 | */ |
| 11 | public class Solution { |
| 12 | public int myAtoi(String str) { |
| 13 | int i = 0, ans = 0, sign = 1, len = str.length(); |
| 14 | while (i < len && str.charAt(i) == ' ') ++i; |
| 15 | if (i < len && (str.charAt(i) == '-' || str.charAt(i) == '+')) { |
| 16 | sign = str.charAt(i++) == '+' ? 1 : -1; |
| 17 | } |
| 18 | for (; i < len; ++i) { |
| 19 | int tmp = str.charAt(i) - '0'; |
| 20 | if (tmp < 0 || tmp > 9) break; |
| 21 | if (ans > Integer.MAX_VALUE / 10 |
| 22 | || (ans == Integer.MAX_VALUE / 10 && (sign == 1 && tmp > 7 || sign == -1 && tmp > 8))) { |
| 23 | return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; |
| 24 | } else { |
| 25 | ans = ans * 10 + tmp; |
| 26 | } |
| 27 | } |
| 28 | return sign * ans; |
| 29 | } |
| 30 | |
| 31 | public static void main(String[] args) { |
| 32 | Solution solution = new Solution(); |