LeetCode # 8 simple questions (small simulation on the line)

Topic: Implementing atoi

class Solution {
public:
    int myAtoi(string str) {
        int start = -1;
        for (int i = 0; i < str.size(); ++i){
            if (str[i] != ' ' && str[i] != 0){
                start = i;
                break;
            }
        }
        if (start == -1)return 0;
                
        long long ans = 0;
        int isLess0 = 1;
        int INT_MINN = -2147483648, INT_MAXX = 2147483647;
        if (str[start] == '-') isLess0 = -1;
        else if (str[start] == '+'){
            isLess0 = 1;
            start += 1;
        }
        int left = isLess0 == -1 ? start + 1 : start;
        for (int i = left; i < str.size(); ++i){
            if (str[i] >= '0' && str[i] <= '9'){
                ans = ans * 10 + (str[i] - '0');
            }
            else{
                break;
            }
            if (ans * isLess0 < INT_MINN){
                return INT_MINN;
            }
            if (ans * isLess0 > INT_MAXX){
                return INT_MAXX;
            }
        }
        return (int)(ans * isLess0);
    }
};

 

Guess you like

Origin www.cnblogs.com/error408/p/11610589.html