Converts a string to an int type, such as "123"--> 123
This topic mainly examines the boundary situation and the illegal input processing, C + + and Java processing is not the same, Java is not the number of integers than Integer.max_value, Java will overflow the number of automatically processed into a valid value, negative also is the same, The offer49 of the Sword refers to the implementation of C + +, directly compared to the number of positive or negative with the largest positive integer and the smallest negative integer value, Java This comparison is not possible. The construction method of the reference integer ("123455") is implemented as follows:
public class _49_strtoint {//Converts a string to an int type, such as "123"-123 public static Boolean valid = FALSE;
public static Boolean Coreflag=false;
public static int strtoint (String num) {if (num = null | | num.length () = 0) {valid = false;
return 0;
int a = 0;
if (Num.charat (0) = = ' + ') {//A = core (num, ' + ');
}else if (num.charat (0) = = '-') {a = core (num, '-');
}else if (Num.charat (0) >= ' 0 ' && num.charat (0) <= ' 9 ') {a = core (num, ' 0 ');
}else{valid = false;
return 0;
} if (Coreflag) {valid = true;
return A;
}else{valid = false;
return 0;
} public static int core (String num, char flag) {int i=0;
if (flag = = ' + ') {i = 1;
} if (flag = = '-') {i=1;
int a = 0;
int temp =a; for (; I<num.length (); i++) {if (!) (
Num.charat (i) >= ' 0 ' && num.charat (i) <= ' 9 ')) {Coreflag = false;
return 0;
Temp =a;
if (flag!= '-') {a = a*10;
A + + (int) (Num.charat (i)-' 0 '); if (Temp > a){///If the current number is small, indicate overflow coreflag = false;
return 0;
}}else {a = a*10;
A-= (int) (Num.charat (i)-' 0 ');/////negative numbers directly subtract without multiplying-1 if (temp < a) {//negative numbers should get smaller, if the current number is larger than before, indicating overflow coreflag = false;
return 0;
}}//} Coreflag = true;
return A; public static void Main (string[] args) {//TODO auto-generated method Stub int a = Strtoint ("-21474836");//-214
7483648 if (valid) {System.out.println (a); }
}
}
Enter the maximum minimum value or the value larger or smaller, and the other illegal digital format test, the output is correct.