forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstringtointeger.java
More file actions
executable file
·39 lines (38 loc) · 1.04 KB
/
stringtointeger.java
File metadata and controls
executable file
·39 lines (38 loc) · 1.04 KB
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
public class Solution {
public int atoi(String str) {
// Start typing your Java solution below
// DO NOT write main() function
str = str.trim();
boolean neg = false;
int start = 0;
if(str.length()==0) return 0;
if(str.charAt(0)=='+'){
start = 1;
}else if(str.charAt(0)=='-'){
start = 1;
neg = true;
}
long ans = 0;
for(int i=start;i<str.length();i++){
if(str.charAt(i)>'9' || str.charAt(i)<'0'){
if(i==start) return 0;
break;
}
else{
long tmp = str.charAt(i)-'0';
ans *= 10L;
ans += tmp;
if(!neg && ans>2147483647L){
return 2147483647;
}else if(neg && ans>2147483648L){
return -2147483648;
}
}
}
if(neg){
return -(int)ans;
}else{
return (int)ans;
}
}
}