Description

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

思路

  • 这个题好像也没有什么简便方法,注意边界条件吧

代码

  • 时间复杂度:O(n)
class Solution {
public:
    const int min_int = -2147483648;
    const int max_int = 2147483647;
    
    int myAtoi(string str) {
        int len = str.size();
        if(len == 0) return 0;
        
        int i = 0;
        while(i < len && str[i] == ' ') i++;
        
        bool isSymbol = false;
        bool isNegative = false;
        if(i < len && str[i] == '-'){
            isSymbol = true;
            isNegative = true;
            i++;
        }
        
        if(!isSymbol && str[i] == '+'){
            isSymbol = true;
            i++;
        }
      
        if(i < len && str[i] >= '0' && str[i] <= '9'){
            long long sum = 0;
            while(i < len && str[i] >= '0' && str[i] <= '9'){
               sum = sum * 10 + (str[i] - '0');
                if(sum > max_int){
                    if(isNegative) return min_int;
                    return max_int;
                }
                i++;
            }

            return isNegative ? -sum : sum;
        }
        else return 0;
    }
};

相关文章:

  • 2021-08-05
  • 2021-12-16
  • 2021-06-23
  • 2021-10-24
  • 2022-01-10
  • 2021-09-01
  • 2021-11-08
猜你喜欢
  • 2021-11-17
  • 2021-07-21
  • 2021-06-29
  • 2022-01-27
  • 2022-03-05
  • 2022-02-04
  • 2021-11-05
相关资源
相似解决方案