|
| 1 | +# [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) |
| 2 | + |
| 3 | +## Description |
| 4 | + |
| 5 | +Implement atoi to convert a string to an integer. |
| 6 | + |
| 7 | +**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. |
| 8 | + |
| 9 | +**Notes:** It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front. |
| 10 | + |
| 11 | +**Spoilers:** |
| 12 | + |
| 13 | +**Requirements for atoi:** |
| 14 | + |
| 15 | +The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. |
| 16 | + |
| 17 | +The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. |
| 18 | + |
| 19 | +If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. |
| 20 | + |
| 21 | +If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned. |
| 22 | + |
| 23 | +**Tags:** Math, String |
| 24 | + |
| 25 | + |
| 26 | +## 思路 |
| 27 | + |
| 28 | +题目大意就是把一个字符串转为整型,但要注意所给的要求,先去除最前面的空格,然后判断正负数,注意正数可能包含`+`,如果之后存在非数字或全为空则返回`0`,而如果合法的值超过int表示的最大范围,则根据正负号返回`INT_MAX`或`INT_MIN`。 |
| 29 | + |
| 30 | +``` java |
| 31 | +public class Solution { |
| 32 | + public int myAtoi(String str) { |
| 33 | + int i = 0, ans = 0, sign = 1, len = str.length(); |
| 34 | + while (i < len && str.charAt(i) == ' ') ++i; |
| 35 | + if (i < len && (str.charAt(i) == '-' || str.charAt(i) == '+')) { |
| 36 | + sign = str.charAt(i++) == '+' ? 1 : -1; |
| 37 | + } |
| 38 | + for (; i < len; ++i) { |
| 39 | + int tmp = str.charAt(i) - '0'; |
| 40 | + if (tmp < 0 || tmp > 9) |
| 41 | + break; |
| 42 | + if (ans > Integer.MAX_VALUE / 10 || ans == Integer.MAX_VALUE / 10 && Integer.MAX_VALUE % 10 < tmp) |
| 43 | + return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE; |
| 44 | + else |
| 45 | + ans = ans * 10 + tmp; |
| 46 | + } |
| 47 | + return sign * ans; |
| 48 | + } |
| 49 | +} |
| 50 | +``` |
0 commit comments