-
Notifications
You must be signed in to change notification settings - Fork 0
/
StringToInteger.java
64 lines (62 loc) · 1.12 KB
/
StringToInteger.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
public class StringToInteger {
public int myAtoi(String str) {
String tmp=str.trim();
long num=0;
int flag=0;
boolean hasSym=false;
for(int i=0;i<tmp.length();i++)
{
int value;
if(hasSym && (tmp.substring(i, i+1).equals("-") || tmp.substring(i, i+1).equals("+")))
return 0;
else
{
if(flag==0 && tmp.substring(i, i+1).equals("-"))
{
flag=1;
hasSym=true;
continue;
}
if(tmp.substring(i, i+1).equals("+"))
{
hasSym=true;
continue;
}
try{
value=Integer.parseInt(tmp.substring(i,i+1));
num=num*10+value;
if(flag==1)
{
if(-num<Integer.MIN_VALUE)
return Integer.MIN_VALUE;
}
else
{
if(num>Integer.MAX_VALUE)
return Integer.MAX_VALUE;
}
}
catch(NumberFormatException exp)
{
if(num!=0)
{
if(flag==0)
return (int)num;
else
return -(int)num;
}
else
return 0;
}
}
}
if(flag==0)
return (int)num;
else
return -(int)num;
}
public static void main(String[] args)
{
System.out.println(new StringToInteger().myAtoi("-1"));
}
}