Skip to content

Commit 283fb88

Browse files
committed
Create String to Integer (atoi)
1 parent 18e5783 commit 283fb88

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
//一些比较刁钻的数据:"" "+" "2147483648"(Expected:2147483647)
2+
public class Solution {
3+
public int myAtoi(String str) {
4+
boolean negative = false;
5+
str = str.trim();
6+
int i=0;
7+
if(i<str.length()&&str.charAt(i)=='+'){++i;} //空串
8+
else if(i<str.length()&&str.charAt(i)=='-') {++i;negative = true;}
9+
long ans = 0;
10+
for(;i<str.length();i++){
11+
int c = str.charAt(i)-'0';
12+
if(c<0||c>9) break; //开始有异常输入会直接跳出,输出0。后面有异常输入,则后面的不被计算
13+
if(!negative){
14+
ans = ans*10+c;
15+
if(ans>Integer.MAX_VALUE) return Integer.MAX_VALUE;
16+
}else{
17+
ans = ans*10-c;
18+
if(ans<Integer.MIN_VALUE) return Integer.MIN_VALUE;
19+
}
20+
}
21+
return (int)ans;
22+
}
23+
}

0 commit comments

Comments
 (0)