-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstringToIntAtoi.java
38 lines (30 loc) · 922 Bytes
/
stringToIntAtoi.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
class Solution {
public int myAtoi(String str) {
if(str == null || str.length() < 1)
return 0;
str = str.trim();
boolean positive = true;
int i = 0, n = str.length();
double result = 0;
if(str.charAt(0) == '+')
i++;
else if(str.charAt(0) == '-'){
positive = false;
i++;
}
while( i < n ){
char temp = str.charAt(i++);
if( temp >= '0' && temp <= '9')
result = 10 * result + (temp - '0');
else
break;
}
if(!positive)
result = -result;
if(result > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
if(result < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
return (int) result;
}
}