1 package myAtoi8;
2 /*
3 * Implement atoi to convert a string to an integer.
4 Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
5 Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
6 Update (2015-02-10):
7 The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.
8 */
9
10 public class Solution {
11 public static int myAtoi(String str) {
12 StringBuilder sb=new StringBuilder();
13 int flag=0;
14 if(str.length()==0)
15 return 0;
16 else{
17 for(int i=0;i<str.length();i++){
18 if(str.charAt(i)<'0'||str.charAt(i)>'9')
19 if(str.charAt(i)=='0'||str.charAt(i)==' ')
20 if (sb.length()==0)
21 continue;
22 else
23 break;
24 else if (str.charAt(i)=='-')
25 if (flag==0){
26 flag=-1;
27 sb.append('0');
28 }
29 else
30 break;
31 else if (str.charAt(i)=='+')
32 if (flag==0){
33 flag=1;
34 sb.append('0');
35 }
36 else
37 break;
38 else
39 break;
40 else
41 sb.append(str.charAt(i));
42 }
43 }
44 if(sb.length()==0)
45 return 0;
46 else if(sb.length()>12)
47 str=sb.substring(sb.length()-12);
48 else
49 str=sb.toString();
50 if (flag==-1)
51 str="-"+str;
52 long result=Long.parseLong(str);
53 System.out.println(result);
54 if (result>2147483647)
55 return 2147483647;
56 else if (result<-2147483648)
57 return -2147483648;
58 else
59 return (int)result;
60
61 }
62 public static void main(String[] args){
63 String str1="";//0
64 String str2="+";//0
65 String str3=" +45555";//45555
66 String str4=" -45555";//-45555
67 String str5="2147483647";//2147483647
68 String str6="2147483648";//2147483647
69 String str7="+-2";//0
70 String str8="-+2";//0
71 String str9="++2";//0
72 String str10="-2147483648";//-2147483648
73 String str11=" - 321";//0
74 String str12=" -11919730356x";//-2147483648
75 String str13="1234567890123456789012345678901234567890";//2147483647
76 System.out.println(myAtoi(str1));
77 System.out.println(myAtoi(str2));
78 System.out.println(myAtoi(str3));
79 System.out.println(myAtoi(str4));
80 System.out.println(myAtoi(str5));
81 System.out.println(myAtoi(str6));
82 System.out.println(myAtoi(str7));
83 System.out.println(myAtoi(str8));
84 System.out.println(myAtoi(str9));
85 System.out.println(myAtoi(str10));
86 System.out.println(myAtoi(str11));
87 System.out.println(myAtoi(str12));
88 System.out.println(myAtoi(str13));
89
90
91 }
92 }