@@ -22,20 +22,53 @@ Output:
2222
2323``` java
2424public int StrToInt(String str) {
25- if (str == null || str. length() == 0 )
26- return 0 ;
27- boolean isNegative = str. charAt(0 ) == ' -' ;
28- int ret = 0 ;
29- for (int i = 0 ; i < str. length(); i++ ) {
30- char c = str. charAt(i);
31- if (i == 0 && (c == ' +' || c == ' -' )) /* 符号判定 */
32- continue ;
33- if (c < ' 0' || c > ' 9' ) /* 非法输入 */
25+ if (str == null )
3426 return 0 ;
35- ret = ret * 10 + (c - ' 0' );
27+ int result = 0 ;
28+ boolean negative = false ;// 是否负数
29+ int i = 0 , len = str. length();
30+ /**
31+ * limit 默认初始化为*负的*最大正整数 ,假如字符串表示的是正数
32+ * 由于int的范围为-2147483648~2147483647
33+ * 那么result(在返回之前一直是负数形式)就必须和这个最大正数的负数来比较来判断是否溢出,
34+ */
35+ int limit = - Integer . MAX_VALUE ;
36+ int multmin;
37+ int digit;
38+
39+ if (len > 0 ) {
40+ char firstChar = str. charAt(0 );// 首先看第一位
41+ if (firstChar < ' 0' ) { // 有可能是 "+" or "-"
42+ if (firstChar == ' -' ) {
43+ negative = true ;
44+ limit = Integer . MIN_VALUE ;// 在负号的情况下,判断溢出的值就变成了 整数的 最小负数了
45+ } else if (firstChar != ' +' )// 第一位不是数字和-只能是+
46+ return 0 ;
47+ if (len == 1 ) // Cannot have lone "+" or "-"
48+ return 0 ;
49+ i++ ;
50+ }
51+ multmin = limit / 10 ;
52+ while (i < len) {
53+ digit = str. charAt(i++ )- ' 0' ;
54+ if (digit < 0 || digit > 9 )
55+ return 0 ;
56+ // 判断溢出
57+ if (result < multmin) {
58+ return 0 ;
59+ }
60+ result *= 10 ;
61+ if (result < limit + digit) {
62+ return 0 ;
63+ }
64+ result -= digit;
65+ }
66+ } else {
67+ return 0 ;
68+ }
69+ // 如果是正数就返回-result(result一直是负数)
70+ return negative ? result : - result;
3671 }
37- return isNegative ? - ret : ret;
38- }
3972```
4073
4174
0 commit comments