author: Blankj blog : http://blankj.com time : 2017/04/23 desc :
| 9 | * </pre> |
| 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(); |
| 33 | System.out.println(solution.myAtoi(" +1")); |
| 34 | System.out.println(solution.myAtoi(" -1")); |
| 35 | System.out.println(solution.myAtoi("")); |
| 36 | System.out.println(solution.myAtoi("a1")); |
| 37 | System.out.println(solution.myAtoi("100000000000000000000")); |
| 38 | System.out.println(solution.myAtoi("-100000000000000000000")); |
| 39 | System.out.println(solution.myAtoi("-3924x8fc")); |
| 40 | System.out.println(solution.myAtoi(String.valueOf(Integer.MIN_VALUE))); |
| 41 | System.out.println(solution.myAtoi(String.valueOf(Integer.MAX_VALUE))); |
| 42 | } |
| 43 | } |
nothing calls this directly
no outgoing calls
no test coverage detected