1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| class Solution { public int myAtoi(String str) { str = str.trim(); if (str.isEmpty()) return 0; int sign = 1; int i = 0; if (str.charAt(0) == '-' || str.charAt(0) == '+'){ sign = (str.charAt(0) == '-')? -1 : 1; if (str.length() < 2 || !Character.isDigit(str.charAt(1))) { return 0; } i++; } int n = 0; while (i < str.length()) { if (Character.isDigit(str.charAt(i))) { int d = str.charAt(i) - '0'; if (n > (Integer.MAX_VALUE - d) / 10) { n = (sign == -1)? Integer.MIN_VALUE : Integer.MAX_VALUE; return n; } n = n*10 + d; } else { break; } i++; } return sign * n; } }
|