forked from yuanx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringToInteger.java
More file actions
54 lines (39 loc) · 935 Bytes
/
StringToInteger.java
File metadata and controls
54 lines (39 loc) · 935 Bytes
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
public class Solution {
public int atoi(String str) {
// Start typing your Java solution below
// DO NOT write main() function
long result = 0;
if(str.length() == 0) return 0;
int max = Integer.MAX_VALUE;
int min = Integer.MIN_VALUE;
int flag = 1;
int current = 0;
while(current<str.length()){
if(str.charAt(current) == ' ')
current++;
else
break;
}
if(current==str.length()) return 0;
if(str.charAt(current) == '-'){
flag = -1;
current++;
}
else if(str.charAt(current) == '+')
current++;
while(current<str.length()){
if(str.charAt(current)>='0' && str.charAt(current)<='9'){
result = result*10 + (str.charAt(current)-'0');
current++;
}
else
break;
}
result *= flag;
if(result>max)
return max;
if(result<min)
return min;
return (int)result;
}
}