微软算法100题20 字符串转整数 atoi

第20 题:
题目:输入一个表示整数的字符串,把该字符串转换成整数并输出。
例如输入字符串"345",则输出整数345

思路:atoi 主要考虑的是对输入的校验和边界处理,以及处理正负符号等

 1 package com.rui.microsoft;
 2 
 3 public class Test20_String2Int {
 4 
 5     public static void main(String[] args) {
 6         int sum = Test20_String2Int.convert("-2147483648");
 7         System.out.println(sum);
 8     }
 9     
10     public static int convert(String input){
11         //remove prefix and suffix empty string
12         input = input.trim();
13         //check null or empty string
14         if(null == input || input.equals("")) return 0;
15         
16         boolean isNegtive = false;
17         //check the start position
18         int start = 0;
19         if('-' == input.charAt(start)) {
20             isNegtive = true;
21             start++;
22         }else if('+' == input.charAt(start)) {
23             isNegtive = false;
24             start++;
25         }
26         
27         int length = input.length();
28         long sum = 0;
29         
30         for(int i = start;i < length; i++){
31             char c = input.charAt(i);
32             if(!isDigit(c))return 0;
33             int tmp = c - '0';
34             sum = sum*10 + tmp;
35         }
36         
37         if(isNegtive){
38             sum = -sum;
39             return sum<Integer.MIN_VALUE? Integer.MIN_VALUE : (int)sum;
40         }else{
41             return sum>Integer.MAX_VALUE? Integer.MAX_VALUE : (int)sum;
42         }
43         
44     }
45     
46     private static boolean isDigit(char c){
47         return c>=48 && c<=57;
48     }
49 
50 }
原文地址:https://www.cnblogs.com/aalex/p/4908357.html