其他分享
首页 > 其他分享> > day26

day26

作者:互联网

剑指 Offer 67. 把字符串转换成整数

 注意一下出界的情况

 1 class Solution {
 2 public:
 3     int strToInt(string str) {
 4        int len = str.size();
 5        if(len == 0)  return 0;
 6        int i = 0;
 7        while(str[i] == ' ' && i < len)  i ++;
 8        if(i >= len)  return 0;
 9        if(!((str[i] >= '0' && str[i] <= '9') || str[i] == '+' || str[i] == '-'))  return 0;
10        int flag = 0;
11        if(str[i] == '-'){
12            flag = 1;
13            i ++;
14        }  
15        else if(str[i] == '+')
16          i ++;
17        int res = 0; int bndry = INT_MAX / 10;
18        while(i < len && (str[i] >= '0' && str[i] <= '9')){
19           if(res > bndry || (res == bndry && str[i] > '7'))
20             return flag == 1 ? INT_MIN : INT_MAX;
21           res = res * 10 + (str[i] - '0');
22           i ++;
23        }
24        if(flag == 1)  return res * (-1);
25        return res;
26     }
27 };

 

标签:return,str,int,res,day26,len,&&
来源: https://www.cnblogs.com/balabalabubalabala/p/16508154.html