Leetcode: 8. String to Integer (atoi)

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;
    }
};

相关推荐