剑指OFFER----面试题67. 把字符串转换成整数

链接:https://leetcode-cn.com/problems/ba-zi-fu-chuan-zhuan-huan-cheng-zheng-shu-lcof/

代码

class Solution {
public:
   int strToInt(string str) {
       int k = 0;
       while (k < str.size() && str[k] == ' ') k++;
       long long number = 0;
       bool is_minus = false;
       if (str[k] == '+') k++;
       else if (str[k] == '-') k++, is_minus = true;

       while (k < str.size() && str[k] >= '0' && str[k] <= '9') {
           int t = str[k] - '0';
           if (number > INT_MAX / 10 || (number == INT_MAX / 10 && t > 7)) { 
               return is_minus ? INT_MIN : INT_MAX;
           }
           number = number * 10 + t;
           k++;
       }
       if (is_minus) number *= -1;
       return (int)number;
   }
};
上一篇:使用嵌套循环以下面金字塔型的格式打印大写字母


下一篇:一道原型上封装的面试题