字符串转整数 (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;
    }
};
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页