8. 字符串转换整数 (atoi)

 1 package leetcode;
 2 
 3 public class demo_8 {
 4     public int myAtoi(String s) {
 5         //判断是整数还是负数
 6         int flag=1;
 7         String ss="";
 8         int a;
 9         //让空格在“+ -”之后
10         int count=0;
11         //让数字在空格和“+ -”之后
12         int number=0;
13         for(int i=0;i<s.length();i++) {
14             if(ss==""&&s.charAt(i)==' ') {
15                 if(count!=0||number==1) {break;}
16                 continue;
17             }
18             if(ss==""&&s.charAt(i)=='-') {
19                 flag=0;
20                 count++;
21                 if(count>1||number==1) {break;}
22                 continue;
23             }
24             if(ss==""&&s.charAt(i)=='+') {
25                 count++;
26                 if(count>1||number==1) {break;}
27                 continue;
28             }
29             if(Integer.valueOf(s.charAt(i))>=48&&Integer.valueOf(s.charAt(i))<=57){
30                 number=1;
31                 if(ss==""&&Integer.valueOf(s.charAt(i))==48) {
32                     continue;
33                 }
34                 else {
35                     ss=ss+s.charAt(i);
36                 }
37             }
38             else {
39                 break;
40             }
41         }
42         try {
43             if(flag==0) {
44                 a=-Integer.valueOf(ss);
45             }
46             else {
47                 a=Integer.valueOf(ss);
48             }
49         } catch (Exception e) {
50             // TODO: handle exception
51             if(flag==0) {
52                 a=-2147483648;
53             }
54             else {
55                 a=2147483647;
56             }
57         }
58         if(ss=="") {return 0;}
59         else {return a;}
60     }
61     public static void main(String[] args) {
62         // TODO Auto-generated method stub
63         demo_8 d8=new demo_8();
64         String s="-91283472332";
65         System.out.println(d8.myAtoi(s));
66     }
67 
68 }

 

posted on 2021-04-17 09:21  一仟零一夜丶  阅读(56)  评论(0)    收藏  举报