-
Description:
-
To convert a string to an integer, you must not use a library function to convert the integer.
-
Input:
-
The input may contain multiple test examples.
For each test case, the input is a valid or invalid string representing an integer N (1 <=n <= 10000000 ).
-
Output:
-
Corresponding to each test case,
If the input is a valid string (that is, an integer), this integer is output.
If the input is an invalid string, the output is "My God ".
Traps:
* ①: Determine whether the first symbol is positive or negative. It is signed or not.
* ②: Judge the illegal input in the string. When the string is invalid, the "My God" is output"
* ③: For overflow judgment, it is necessary to use the biginteger class for calculation.
Package test1058; import Java. math. biginteger; import Java. util. extends; public class main {public static void main (string [] ARGs) {extends = new loads (system. in); While (partial. hasnext () {string = success. next (); biginteger = stringtoint (string); If (biginteger = NULL) {system. out. println ("My God");} else {system. out. println (biginteger) ;}}/ *** ①: determines whether the first symbol is positive or negative. If it is signed or does not exist, ② determines whether illegal input in the string is obtained, when the string is invalid, "My God" is output * ③: The overflow condition is determined, therefore, it is necessary to use the biginteger class for calculation ** @ Param Str * @ return */public static biginteger stringtoint (string Str) {Boolean flag = true; If (Str. length () = 0) {return NULL;} Char [] C = Str. tochararray (); int Index = 0; biginteger result = biginteger. valueof (0); If (C [Index] = '+') {index ++;} else if (C [Index] = '-') {index ++; flag = false;} while (index <Str. length () {If (C [Index] <'0' | C [Index]> '9') {return NULL ;} // result = Result * 10 + C [Index]-'0'; Result = (result. multiply (biginteger. valueof (10 ))). add (biginteger. valueof (C [Index]-'0'); index ++;} If (flag = false) {// result * =-1; Result = result. divide (biginteger. valueof (-1);} return result ;}}
Converts a string to an integer.