File tree 1 file changed +49
-0
lines changed
1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*******************************************************
2
+ * @author SAGAR PAUL (paulsagar1a)
3
+ * @category string
4
+ *******************************************************/
5
+ /*The atoi() function takes a string (which represents an integer)
6
+ as an argument and returns its value.*/
7
+ package string ;
8
+
9
+ public class AToI {
10
+
11
+ public int atoi (String str ) {
12
+ if (str == null || str .length () < 1 )
13
+ return 0 ;
14
+ //trim white space
15
+ str = str .trim ();
16
+ char flag = '+' ;
17
+ int i = 0 ;
18
+ if (str .charAt (i ) == '-' ) {
19
+ flag = '-' ;
20
+ i ++;
21
+ } else if (str .charAt (i ) == '+' ) {
22
+ i ++;
23
+ }
24
+
25
+ long result = 0 ;
26
+ for (;i <str .length (); i ++) {
27
+ result = result *10 + (str .charAt (i ) - '0' );
28
+ }
29
+
30
+ if (flag == '-' ) {
31
+ result = -result ;
32
+ }
33
+
34
+ //handle MAX/MIN
35
+ if (result > Integer .MAX_VALUE )
36
+ return Integer .MAX_VALUE ;
37
+ if (result < Integer .MIN_VALUE )
38
+ return Integer .MIN_VALUE ;
39
+
40
+ return (int )result ;
41
+ }
42
+
43
+ public static void main (String [] args ) {
44
+ // TODO Auto-generated method stub
45
+ AToI obj = new AToI ();
46
+ System .out .println (obj .atoi ("-14657" ));
47
+ }
48
+
49
+ }
You can’t perform that action at this time.
0 commit comments