Question 20th:
Title: Enter a String representing an integer to convert the string to an integer and output.
For example, the input string "345", the output integer 345
Idea: Atoi is mainly concerned with the calibration and boundary processing of the input, as well as the processing of positive and negative symbols.
1 PackageCom.rui.microsoft;2 3 Public classTest20_string2int {4 5 Public Static voidMain (string[] args) {6 intsum = Test20_string2int.convert ("2147483648");7 System.out.println (sum);8 }9 Ten Public Static intconvert (String input) { One //remove prefix and suffix empty string Ainput =Input.trim (); - //check null or empty string - if(NULL= = Input | | Input.equals (""))return0; the - BooleanIsnegtive =false; - //Check the start position - intStart = 0; + if('-' = =Input.charat (start)) { -Isnegtive =true; +start++; A}Else if(' + ' = =Input.charat (start)) { atIsnegtive =false; -start++; - } - - intLength =input.length (); - Longsum = 0; in - for(inti = start;i < length; i++){ to Charc =Input.charat (i); + if(!isdigit (c))return0; - intTMP = C-' 0 '; thesum = sum*10 +tmp; * } $ Panax Notoginseng if(isnegtive) { -sum =-sum; the returnSum<integer.min_value? Integer.min_value: (int) sum; +}Else{ A returnSum>integer.max_value? Integer.max_value: (int) sum; the } + - } $ $ Private Static BooleanIsDigit (Charc) { - returnc>=48 && c<=57; - } the -}
Microsoft algorithm 100 questions 20 string to integer atoi