【LeetCode 8】字符串转换整数 (atoi)

题目链接

【题解】

注意越界的处理就好 简单题 还有。。 正的-2^31不能由2^31取相反数得到,因为正的int最多到2^31-1

【代码】

class Solution {
public:
    bool isdigit(char key){
        return (key>='0') && (key<='9');
    }
    
    int myAtoi(string str) {
        int MAX_INT = (int)((1ll<<31)-1);
        int MIN_INT = (int)(-(1ll<<31));
        cout<<MAX_INT<<endl;
        cout<<MIN_INT<<endl;
        int len = str.size();
        int idx = -1;
        int f = 1;
        for (int i = 0;i<len;i++){
            if (str[i]!=' '){
                if (str[i]=='-'){
                    f = -1;
                    idx = i+1;
                }else if (str[i]=='+'){
                    idx = i+1;
                }else if (isdigit(str[i])){
                    idx = i;
                }
                break;
            }
        }
        if (idx==-1) return 0;
        if (!isdigit(str[idx])) return 0;
        int i = idx;
        int temp = 0;
        /*
            2147483647
            -2147483648
        */
        while (i<len && isdigit(str[i])){
            int x = str[i]-'0';
            if (f==-1){
                if (MIN_INT/10!=temp){
                    if (MIN_INT/10>temp)
                        return MIN_INT;
                }else{
                    //MIN_INT/10==(-temp)
                    if (x>8){
                        return MIN_INT;
                    }
                }
            }else{
                if (MAX_INT/10!=temp){
                    if (MAX_INT/10<temp){
                        return MAX_INT;
                    }
                }else{
                    if (x>7) return MAX_INT;
                }
            }
            //not exceed limitation
            temp = temp*10+f*x;
            i++;
        }
        return temp;
    }
};
posted @ 2019-11-03 23:56  AWCXV  阅读(125)  评论(0编辑  收藏  举报