leetcode之atoi

来源:互联网 发布:淘宝店铺宝箱怎么设置 编辑:程序博客网 时间:2024/05/16 01:09
class Solution {
public:
    int atoi(const char *str) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (str == NULL) {
            return 0;
        }
        bool isNegtive = false;
        char* start = const_cast<char*>( str);
        int len = strlen(str);
        char* end = start+len-1;
        if (*start == '-') {
            isNegtive = true;
            start++;
        }
        if (*start=='+') {
            isNegtive = false;
            start++;
        }
        int res = 0;
        bool first = true;
        while (start <= end) {
            if (first&&*start=='0') {
                start++;
            }
            if (isdigit(*start)) {
                first = false;
                res = res*10+(*start-'0');
               
            }
             start++;
        }
        if (isNegtive) {
            res = 0-res;
        }
        return res;
    }
};
原创粉丝点击