剑指 Offer 67. 把字符串转换成整数
# 剑指 Offer 67. 把字符串转换成整数 (opens new window)
# 1.模拟
分析:用long类型来存储当前字符串转化的int值,直接用大于小于号进行越界判断。
class Solution {
public int strToInt(String str) {
str=str.trim();
if(str.length()==0) return 0;
int minus=1;
if(str.charAt(0)=='+'||str.charAt(0)=='-'){
if(str.length()==1) return 0;
minus=str.charAt(0)=='+'?1:-1;
str=str.substring(1);
}
int res=0;
if(str.charAt(0)>='0'&&str.charAt(0)<='9'){
int index=0;
long sum=0;
while(index<str.length()&&str.charAt(index)>='0'&&str.charAt(index)<='9'){
int a=str.charAt(index)-'0';
sum=sum*10+a;
index++;
if(minus==1&&sum>=Integer.MAX_VALUE){
res=Integer.MAX_VALUE;
break;
}
if(minus==-1&&sum*(-1)<=Integer.MIN_VALUE){
res=Integer.MIN_VALUE;
break;
}
}
if(res==0) res=(int) sum;
}
return res*minus;
}
}
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
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
编辑 (opens new window)
上次更新: 2023/12/15, 15:49:57