LeetCode 8. String to Integer (atoi)

很简单。

class Solution {
public:
    int myAtoi(string str) {
        int i=0,c=1;long long ans=0;
        while(str[i]==' ') i++;
        if((str[i]>'9'||str[i]<'0')&&(str[i]!='-')&&(str[i]!='+')) return 0;
        if (str[i]=='-'&&str[i+1]>='0'&&str[i+1]<='9') {c=-1;i++;}
        if (str[i]=='+'&&str[i+1]>='0'&&str[i+1]<='9') {i++;}
        while(str[i]>='0'&&str[i]<='9'){
            ans=ans*10+(str[i]-'0')*c;
            if (ans>INT_MAX) return INT_MAX;
            else if (ans<INT_MIN) return INT_MIN;
            i++;
        }
        return ans ; 
    }
};

 

posted @ 2018-08-07 12:25  Travelller  阅读(110)  评论(0)    收藏  举报