Skip to content

Commit f3b0839

Browse files
committed
atoi program: 1st commit
1 parent 4c9446f commit f3b0839

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

string/AToI.java

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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+
}

0 commit comments

Comments
 (0)