|
| 1 | +/* |
| 2 | + Author: King, wangjingui@outlook.com |
| 3 | + Date: Dec 14, 2014 |
| 4 | + Problem: String to Integer (atoi) |
| 5 | + Difficulty: Easy |
| 6 | + Source: https://oj.leetcode.com/problems/string-to-integer-atoi/solution/ |
| 7 | + Notes: |
| 8 | + Implement atoi to convert a string to an integer. |
| 9 | + Hint: Carefully consider all possible input cases. If you want a challenge, please do not |
| 10 | + see below and ask yourself what are the possible input cases. |
| 11 | + Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). |
| 12 | + You are responsible to gather all the input requirements up front. |
| 13 | +
|
| 14 | + Requirements for atoi: |
| 15 | + The function first discards as many whitespace characters as necessary until the first |
| 16 | + non-whitespace character is found. Then, starting from this character, takes an optional |
| 17 | + initial plus or minus sign followed by as many numerical digits as possible, and interprets |
| 18 | + them as a numerical value. |
| 19 | + The string can contain additional characters after those that form the integral number, which |
| 20 | + are ignored and have no effect on the behavior of this function. |
| 21 | + If the first sequence of non-whitespace characters in str is not a valid integral number, or |
| 22 | + if no such sequence exists because either str is empty or it contains only whitespace characters, |
| 23 | + no conversion is performed. |
| 24 | + If no valid conversion could be performed, a zero value is returned. If the correct value is out |
| 25 | + of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned. |
| 26 | +
|
| 27 | + Solution: 1. To deal with overflow, inspect the current number before multiplication. |
| 28 | + If the current number is greater than 214748364, we know it is going to overflow. |
| 29 | + On the other hand, if the current number is equal to 214748364, |
| 30 | + we know that it will overflow only when the current digit is greater than or equal to 8.. |
| 31 | + */ |
| 32 | + |
| 33 | +publicclassSolution { |
| 34 | +publicintatoi(Stringstr) { |
| 35 | +if (str ==null)return0; |
| 36 | +inti =0; |
| 37 | +booleansign =true; |
| 38 | +str =str.trim(); |
| 39 | +intn =str.length(); |
| 40 | +if (i <n && (str.charAt(0) =='+' ||str.charAt(0) =='-')) { |
| 41 | +if (str.charAt(0) =='+')sign =true; |
| 42 | +elsesign =false; |
| 43 | + ++i; |
| 44 | + } |
| 45 | +intres =0; |
| 46 | +while (i <n &&Character.isDigit(str.charAt(i))) { |
| 47 | +if(res >Integer.MAX_VALUE /10 || (res ==Integer.MAX_VALUE /10 &&str.charAt(i) -'0' >Integer.MAX_VALUE %10)){ |
| 48 | +returnsign ?Integer.MAX_VALUE :Integer.MIN_VALUE ; |
| 49 | + } |
| 50 | +res =res *10 +str.charAt(i) -48; |
| 51 | + ++i; |
| 52 | + } |
| 53 | +returnsign ?res : -res; |
| 54 | + } |
| 55 | +} |