code4offer-13 把字符串转换成整数

Unsolved

问题描述

分析

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
public int StrToInt(String str) {
int len = str.length();
if (len == 0) return 0;
int numLength = len;
int sign = 1;
if (str.charAt(0) == '-' || str.charAt(0) == '+') --numLength;
if (str.charAt(0) == '-') {
sign = -1;
}

long result = 0;
int carry = 1;

for(int i = len - 1; i >= len - numLength; --i) {
if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
if (sign > 0 && result > Integer.MAX_VALUE - (str.charAt(i)-'0') * carry) {
return 0;
}else if (sign < 0 && -result < Integer.MIN_VALUE + (str.charAt(i)-'0') * carry) {
return 0;
}
result += (str.charAt(i)-'0') * carry;
carry *= 10;
} else {
return 0;
}
}
return (int)result * sign;
}