8. String to Integer (atoi)
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
注意异常的输入:
“” “acbd” “+-123” “ 111” “0” “ “ “+-+-“ “-1” “ -0012a42” “-11919730356x” “999999999999999999999999999999” “9223372036854775809”
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 class Solution { public int myAtoi (String str) { if (str.length() == 0 ){ return 0 ; } int index = 0 ; int positive = 1 ; long result = 0 ; while (index < str.length() && str.charAt(index) == ' ' ){ index ++; } if (index == str.length()){ return 0 ; } if (str.charAt(index) == '-' || str.charAt(index) == '+' ){ positive = str.charAt(index)=='-' ? -1 :1 ; index ++; } if (index == str.length()){ return 0 ; } while (index < str.length()){ if (str.charAt(index) < '0' || str.charAt(index) > '9' ){ break ; } result = result * 10 + str.charAt(index)-'0' ; if (result*positive > Integer.MAX_VALUE){ return Integer.MAX_VALUE; } if (result*positive < Integer.MIN_VALUE){ return Integer.MIN_VALUE; } index ++; } result = result*positive; return (int ) result; } }
感觉我的答案还是不够简练,这里贴上discuss区里得分最高的solution:
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 public int myAtoi (String str) { int index = 0 , sign = 1 , total = 0 ; if (str.length() == 0 ) return 0 ; while (str.charAt(index) == ' ' && index < str.length()) index ++; if (str.charAt(index) == '+' || str.charAt(index) == '-' ){ sign = str.charAt(index) == '+' ? 1 : -1 ; index ++; } while (index < str.length()){ int digit = str.charAt(index) - '0' ; if (digit < 0 || digit > 9 ) break ; if (Integer.MAX_VALUE/10 < total || Integer.MAX_VALUE/10 == total && Integer.MAX_VALUE %10 < digit) return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; total = 10 * total + digit; index ++; } return total * sign; }