描述
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 andask yourself what are the possible input cases.Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You areresponsible to gather all the input requirements up front.Requirements for atoi:The function first discards as many whitespace characters as necessary until the first non-whitespacecharacter is found. Then, starting from this character, takes an optional initial plus or minus sign followedby 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 suchsequence exists because either str is empty or it contains only whitespace characters, no conversion isperformed.If no valid conversion could be performed, a zero value is returned. If the correct value is out of therange of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.分析细节题。注意几个测试用例:1. 不规则输入,但是有效,”-3924x8fc”,” + 413”,2. 无效格式,” ++c”, ” ++1”
3. 溢出数据,”2147483648”代码
1 public class StringtoInteger { 2 static int INT_MAX = 2147483647; 3 static int INT_MIN = -2147483648; 4 5 public static void main(String[] args) { 6 // TODO Auto-generated method stub 7 String str = "-39x24x8fc"; 8 System.out.println(atoi(str)); 9 }10 // LeetCode, String to Integer (atoi)11 // 时间复杂度 O(n),空间复杂度 O(1)12 13 public static int atoi(String str) {14 int num = 0;15 int sign = 1;16 int n = str.length();17 int i = 0;18 while (str.charAt(i) == ' ' && i < n)19 i++; // 去空格20 if (str.charAt(i) == '+')21 i++; // 判符号22 if (str.charAt(i) == '-') { // 判符号-23 sign = -1; // sign符号24 i++;25 }26 for (; i < n; i++) { //27 if (str.charAt(i) < '0' || str.charAt(i) > '9')28 // break; //跳出本循环 得到部分数字29 continue; // 跳出本次循环,不运行循环内的下面程序,然后跳到下次循环。得到全部数字30 if (num > INT_MAX / 10 || 31 (num == INT_MAX / 10 && (str.charAt(i) - '0') > INT_MAX % 10)) { // 判超限32 return sign == -1 ? INT_MIN : INT_MAX;33 }34 num = num * 10 + str.charAt(i) - '0';35 }36 return num * sign;37 }38 39 }