-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathString to Integer (atoi).java
46 lines (45 loc) · 1.09 KB
/
String to Integer (atoi).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
class Solution {
public int myAtoi(String s) {
s = s.trim();
if(s.length() == 0){
return 0;
}
boolean sign = true;
long ans =0;
for(int i = 0;i<s.length();i++){
char ch = s.charAt(i);
if(i == 0){
if(ch == '-'){
sign = false;
continue;
}else if(ch == '+'){
sign = true;
continue;
}else{
sign = true;
}
}
if(ch >= '0' && ch <= '9'){
int dig = ch - '0';
ans = ans * 10 + dig;
if(sign == false){
long check = -ans;
if(check<Integer.MIN_VALUE){
return Integer.MIN_VALUE;
}}else{
long check = ans;
if(check>Integer.MAX_VALUE){
return Integer.MAX_VALUE;
}
}
}
else{
break;
}
}
if(sign == false){
ans = -ans;
}
return (int)ans;
}
}