字符串转整数 (atoi)

class Solution {
public:
    int myAtoi(string str) {
        int64_t ans = 0;
        int first = 0;

        for (auto ch : str) {

            if (first == 0 && ch == ' ') {
                continue;
            } else if (first == 0 && ch == '-') {
                first = -1;
            } else if (first == 0 && ch == '+') {
                first = 1;
            } else if ((ch -  '0') >= 0 && (ch - '0') <= 9) {
                ans = ans*10 + (ch - '0');

                if (first == 0) {
                    first = 1;
                }
                if (ans*first >= INT_MAX) {
                    return INT_MAX;
                }
                if (ans*first <= INT_MIN) {
                    return INT_MIN;
                }

            } else {
                break;
            }
        }
        if (first == -1) {
            ans *= -1;
        }
        return ans;
    }
};

你可能感兴趣的:(leetcode)