77
77
``` python
78
78
class Solution :
79
79
def strToInt (self , str : str ) -> int :
80
- if str is None or len ( str .strip()) == 0 :
80
+ if not str :
81
81
return 0
82
- str = str .strip()
83
- i = res = 0
84
- negative = str[0 ] == ' -'
85
- i += 1 if str[0 ] == ' -' or str[0 ] == ' +' else 0
86
- while i < len (str ) and str[i].isdigit():
87
- r = int (str[i])
88
- if res > (2 ** 31 // 10 ) or (res == (2 ** 31 // 10 ) and r > 7 ):
89
- return 2 ** 31 - 1 if not negative else - 2 ** 31
90
- res = res * 10 + r
82
+ n = len (str )
83
+ if n == 0 :
84
+ return 0
85
+ i = 0
86
+ while str[i] == ' ' :
87
+ i += 1
88
+ if i == n:
89
+ return 0
90
+ sign = - 1 if str[i] == ' -' else 1
91
+ if str[i] in [' -' , ' +' ]:
92
+ i += 1
93
+ res, flag = 0 , (2 ** 31 - 1 ) // 10
94
+ while i < n:
95
+ if not str[i].isdigit():
96
+ break
97
+ c = int (str[i])
98
+ if res > flag or (res == flag and c > 7 ):
99
+ return 2 ** 31 - 1 if sign > 0 else - 2 ** 31
100
+ res = res * 10 + c
91
101
i += 1
92
- return - res if negative else res
102
+ return sign * res
93
103
```
94
104
95
105
### ** Java**
@@ -99,29 +109,26 @@ class Solution:
99
109
``` java
100
110
class Solution {
101
111
public int strToInt (String str ) {
102
- if (str == null || " " . equals(str. trim())) {
103
- return 0 ;
104
- }
105
- str = str. trim();
106
- int res = 0 , i = 0 , flag = 1 ;
112
+ if (str == null ) return 0 ;
107
113
int n = str. length();
108
- if (str . charAt(i) == ' - ' ) {
109
- flag = - 1 ;
110
- }
111
- if (str . charAt(i) == ' - ' || str . charAt(i) == ' + ' ) {
112
- ++ i;
114
+ if (n == 0 ) return 0 ;
115
+ int i = 0 ;
116
+ while (str . charAt(i) == ' ' ) {
117
+ // 仅包含空格
118
+ if ( ++ i == n) return 0 ;
113
119
}
114
- while (i < n && Character . isDigit(str. charAt(i))) {
115
- int r = str. charAt(i) - ' 0' ;
116
- // 溢出处理
117
- if (res > Integer . MAX_VALUE / 10 || (res == Integer . MAX_VALUE / 10 ) && r > 7 ) {
118
- return flag > 0 ? Integer . MAX_VALUE : Integer . MIN_VALUE ;
119
- }
120
- res = res * 10 + r;
121
- ++ i;
120
+ int sign = 1 ;
121
+ if (str. charAt(i) == ' -' ) sign = - 1 ;
122
+ if (str. charAt(i) == ' -' || str. charAt(i) == ' +' ) ++ i;
123
+ int res = 0 , flag = Integer . MAX_VALUE / 10 ;
124
+ for (; i < n; ++ i) {
125
+ // 非数字
126
+ if (str. charAt(i) < ' 0' || str. charAt(i) > ' 9' ) break ;
127
+ // 溢出判断
128
+ if (res > flag || (res == flag) && str. charAt(i) > ' 7' ) return sign > 0 ? Integer . MAX_VALUE : Integer . MIN_VALUE ;
129
+ res = res * 10 + (str. charAt(i) - ' 0' );
122
130
}
123
-
124
- return flag > 0 ? res : - res;
131
+ return sign * res;
125
132
}
126
133
}
127
134
```
0 commit comments