Leetcode: String to Integer
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. 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. spoilers alert... click to show requirements for atoi. Requirements for atoi: 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. 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. 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. 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.
抠细节的题目,特别是 Integer.MIN_VALUE 与 Integer.MAX_VALUE的绝对值并不一样大. 一般要分开处理,但我这里16-17行统一处理也是可行的,原因在于用的是>号,当res 绝对值为2147483647时,给res加正号或者加负号都是可以的,不需要特殊处理;只有当res绝对值为2147483648或更大时才需要特别处理,如果是正数则处理为Integer.MAX_VALUE,如果是负数则处理为Integer.MIN_VALUE(与直接给2147483648加上负号效果一样)。整数一般有两点,一个是正负符号问题,另一个是整数越界问题。
1 public class Solution { 2 public int atoi(String str) { 3 int res = 0; 4 if (str==null || str.length()==0) return res; 5 str = str.trim(); 6 if (str.length() == 0) return res; 7 boolean isNeg = false; 8 for (int i=0; i<str.length(); i++) { 9 if (i == 0 && str.charAt(i) == '+') continue; 10 else if (i == 0 && str.charAt(i) == '-') { 11 isNeg = true; 12 continue; 13 } 14 else if (str.charAt(i)>='0' && str.charAt(i)<='9') { 15 int digit = (int)(str.charAt(i) - '0'); 16 if (res > (Integer.MAX_VALUE - digit) / 10) { 17 return isNeg? Integer.MIN_VALUE : Integer.MAX_VALUE; 18 } 19 res = res * 10 + digit; 20 } 21 else break; 22 } 23 return isNeg? -res : res; 24 } 25 }
转载一个不错的解法(跟我差不多):
1 public int atoi(String str) { 2 if(str==null) 3 { 4 return 0; 5 } 6 str = str.trim(); 7 if(str.length()==0) 8 return 0; 9 boolean isNeg = false; 10 int i = 0; 11 if(str.charAt(0)=='-' || str.charAt(0)=='+') 12 { 13 i++; 14 if(str.charAt(0)=='-') 15 isNeg = true; 16 } 17 int res = 0; 18 while(i<str.length()) 19 { 20 if(str.charAt(i)<'0'||str.charAt(i)>'9') 21 break; 22 int digit = (int)(str.charAt(i)-'0'); 23 if(isNeg && res>-((Integer.MIN_VALUE+digit)/10)) 24 return Integer.MIN_VALUE; 25 else if(!isNeg && res>(Integer.MAX_VALUE-digit)/10) 26 return Integer.MAX_VALUE; 27 res = res*10+digit; 28 i++; 29 } 30 return isNeg?-res:res; 31 }