File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ int strToInt (string str) {
4+ int res = 0 , bndry = INT_MAX / 10 ;
5+ int i = 0 , sign = 1 , length = str.size ();
6+ if (length == 0 ) {
7+ return 0 ;
8+ }
9+ // 删除首部空格
10+ while (str[i] == ' ' ) {
11+ if (++i == length) {
12+ return 0 ;
13+ }
14+ }
15+ // 若有负号则标识符号位
16+ if (str[i] == ' -' ) {
17+ sign = -1 ;
18+ }
19+ if (str[i] == ' -' || str[i] == ' +' ) {
20+ i++;
21+ }
22+ for (int j = i; j < length; j++) {
23+ if (str[j] < ' 0' || str[j] > ' 9' ) {
24+ break ;
25+ }
26+ // res>214748364越界;res=214748364且str[j] > '7'越界
27+ if (res > bndry || res == bndry && str[j] > ' 7' ) {
28+ return sign == 1 ? INT_MAX : INT_MIN;
29+ }
30+ // 从左向右遍历数字并更新结果
31+ res = res * 10 + (str[j] - ' 0' );
32+ }
33+ return sign * res;
34+ }
35+ };
You can’t perform that action at this time.
0 commit comments