leetcode08--String to Integer(实现字符串到整数的转换)

实现字符串到整数的转换

注意事项:

下面给出这道题应该注意的一些细节:

1. 字符串“ 123 ” = 123;

2. 字符串“+123” = 123;

3. 字符串“-123” = -123;

4. 字符串“-” = 0;“+” = 0;

5. 字符串“123-” = 123;

6. 字符串“21474836478” = 2147483647(Integer.MAX_VALUE)

7. 其余情况都是非法输入,一律返回0;*/
 1 public class Main05 {
 2     public static void main(String[] args) {
 3         Scanner scan = new Scanner(System.in);
 4         while (scan.hasNext()){
 5             String str = scan.nextLine();
 6             System.out.println(atoi(str));
 7 
 8         }
 9     }
10 
11     private static int atoi(String str) {
12         if(str == null || str.trim().length() ==0){
13             return 0;
14         }
15         str = str.trim();
16         String res = "";
17         int index = 0;
18         String minStr = "";
19         if(str.charAt(0) =='-'){
20             minStr = "-";
21             index++;
22         }else if(str.charAt(0) =='+'){
23 
24             index++;
25         }
26         for(int i=index;i<str.length();i++){
27             if(str.charAt(i)>='0' && str.charAt(i)<='9'){
28                 res +=str.charAt(i);
29             }else {
30                 break;
31             }
32         }
33         if(res == ""){
34             return 0;
35         }
36         if(Long.valueOf(minStr+res)>Integer.MAX_VALUE){
37             return Integer.MAX_VALUE;
38         }
39         if(Long.valueOf(minStr+res)<Integer.MIN_VALUE){
40             return Integer.MIN_VALUE;
41         }
42 
43         return Integer.valueOf(minStr+res);
44     }
45 
46 }

 



posted @ 2018-04-07 11:16  huster-stl  阅读(281)  评论(0编辑  收藏  举报