leetcode problem 8: String to Integer (atoi)

class Solution {
public:
    int myAtoi(string str) {
        int index = -1;
        int result = 0;
        int base = 10;
        int ssize = str.size();
        bool negtive = false;
        while (++index < ssize && (str[index] == ' '));
        if (index < ssize){
            if (str[index] == '+')
            {
                ++index;
            }
            else if (str[index] == '-')
            {
                negtive = true; ++index;
            }
        }
        if (index < ssize && str[index] == '0'){
            ++index;
            if (index < ssize && (str[index] == 'X' || str[index] == 'x')){
                base = 16;
                ++index;
            }
        }
        while (index < ssize){
            char c = str[index];
            int v = 0;
            if (base == 10){
                if (c >= '0' && c <= '9'){
                    v = c - '0';
                }
                                else {
                    break;
                }
            }
            else if (base == 16){
                if (c >= '0' && c <= '9'){
                    v = c - '0';
                }
                else if (c >= 'a' && c <= 'f'){
                     v = 10 + c - 'a';
                }
                else if (c >= 'A' && c <= 'F'){
                     v = 10 + c - 'A';
                }
                else {
                    break;
                }
            }
            if (negtive){
                if ((INT_MIN + v)/base > (result)){
                    result = INT_MIN;
                    break;
                }
                else {
                    result *= base;
                    result -= v;
                }
            }
            else {
                if ((INT_MAX - v)/base < (result)){
                    result = INT_MAX;
                    break;
                }
                else {
                    result *= base;
                    result += v;
                }
            }
            index ++;
        }
        return result;
    }
};

  

posted @ 2017-11-18 21:07  nosaferyao  阅读(135)  评论(0编辑  收藏  举报