leetcode实现atoi

#include <limits.h>
#include <ctype.h>
#include <iostream>
class Solution {
public:
    int myAtoi(string str) {
        int pos;
        bool negative;
        if (false == get_digital(str, pos, negative)) {
            return 0;
        }
        int res = 0;
        char digital_array[MAX_SIZE] = "";
        if (false == check_validity(str, pos, negative, digital_array, res)) {
            return res;
        }
        compute_res(negative, digital_array, res);
        return res;
    }
private:
    bool get_digital(const std::string &str, int &pos, bool &negative) {
        pos = 0;
        negative = false;
        char ch = 0;
        bool zero = false;
        for (;(ch = str[pos]);pos++) {
            if (' ' == ch) {
                if (true == zero) {
                    return false;
                }
                continue;
            }
            if (!isdigit(ch) && ('+' != ch) && ('-' != ch)) {
                return false;
            }
            if ('0' == ch) {
                zero = true;
                continue;
            }
            if (isdigit(ch)) {
                return true;
            }
            if (true == zero) {
                return false;
            }
            negative = ('-' == ch);
            pos++;
            return true;
        }
        return true;
    }
    bool check_validity(const std::string &str, int pos, bool negative, char *digital_array, int &res) {
        static char INT_MAX_ARRAY[MAX_SIZE] = "2147483648";
        static const int NUM_MAX_SIZE = 10;
        char ch = 0;
        int i = 0;
        for (;(ch = str[pos]);pos++) {
            if ('0' != ch) {
                break;
            }
        }
        while ((ch = str[pos]) && isdigit(ch) && i < MAX_SIZE) {
            digital_array[i++] = ch;
            pos++;
        }
        if (i > NUM_MAX_SIZE || (NUM_MAX_SIZE == strlen(digital_array) && strcmp(digital_array, INT_MAX_ARRAY) >= 0)) {
            if (true == negative) {
                res = INT_MIN;
                return false;
            }
            res = INT_MAX;
            return false;
        }
        return true;
    }
    void compute_res(bool negative, const char *digital_array, int &res) {
        int sum = 0;
        int i = 0;
        char ch = 0;
        while (ch = digital_array[i]) {
            sum = (sum << 1) + (sum << 3) + (ch - '0');
            i++;
        }
        if (true == negative) {
            res = -sum;
            return;
        }
        res = sum;
    }
private:
    const static size_t MAX_SIZE = 16;
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值