We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 18e5783 commit 283fb88Copy full SHA for 283fb88
CuiYanling/String to Integer (atoi)
@@ -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