java stoi

 1 package string.string1_4;
 2 
 3 import java.util.Scanner;
 4 
 5 public class StrToInt
 6 {
 7     /**
 8      * 将str转换为int整数
 9      * 1. 处理输入为空
10      * 2. 处理输入有非法字符
11      * 3. 处理溢出
12      * 4. 处理开头的空格
13      */
14     public static int stoi(String str)
15     {
16         if(str == null || str.equals(""))
17             return 0 ;
18         int i = 0;
19         while (str.charAt(i) == ' ')
20             i++ ;
21 
22         boolean isPositive = true ;
23 
24         if(!check(str.charAt(i)))
25         {
26             //检查整数开始的第一个字符是否为-或+, 如果结果为false则说明输入非法
27             if(str.charAt(i) != '-' && str.charAt(i) != '+')
28                 return 0 ;
29             if(str.charAt(i) == '-')
30                 isPositive = false ;
31             i++ ;
32         }
33 
34         int theNumber = 0 ;
35 
36         for( ; i<str.length() ; i++)
37         {
38             char ch = str.charAt(i) ;
39             int x = ch-48 ;
40             if(!check(ch))  //检查合法性
41                 return 0 ;
42             boolean overflow = false ;
43             //比较当前数字是否和max/10, 大于说明溢出, 如果等于, 那么就比较x和max%10的余数,如果大于, 说明溢出
44             if(isPositive && (theNumber > Integer.MAX_VALUE/10 || (theNumber == Integer.MAX_VALUE/10 && x >= Integer.MAX_VALUE%10)))
45                 overflow = true ;
46             //由于java没有unsigned类型, 因此只能将当前数字转换为负数进行等价比较
47             else if(-theNumber < (Integer.MIN_VALUE)/10 || (-theNumber == Integer.MIN_VALUE/10 && -x <= Integer.MIN_VALUE%10))
48                 overflow = true ;
49             if(overflow)
50                 return isPositive ? Integer.MAX_VALUE : Integer.MIN_VALUE ;
51             else
52                 theNumber = theNumber*10 + x ;
53         }
54 
55         return isPositive ? theNumber : -theNumber ;
56     }
57 
58     /**
59      * 检查是否是合法字符, 合法字符仅包括0-9
60      */
61     private static boolean check(char ch)
62     {
63         if(ch>=48 && ch <=57)
64             return true ;
65         return false ;
66     }
67 
68     public static void main(String[] args) {
69         Scanner sc = new Scanner(System.in) ;
70 
71         while (true)
72         {
73             String line = sc.nextLine() ;
74             int x = stoi(line) ;
75 
76             System.out.println(x);
77         }
78     }
79 }
原文地址:https://www.cnblogs.com/iamzhoug37/p/5634321.html