LeetCode 8. String to Integer (atoi)

来源:互联网 发布:买家淘宝换名字怎么改 编辑:程序博客网 时间:2024/05/28 15:56


There are quite a lot of details to pay attentions to. But, the most important one is : watch out overflow..... Thus, the res value should be long long int type.

Better to compare with this question : http://blog.csdn.net/github_34333284/article/details/51171908

    int myAtoi(string str) {            if(str.size() == 0) return 0;    int i = 0;    long long int res = 0;    bool negative = false;    while(i < str.size() && str[i] == ' ') {        i++;    }    if(str[i] == '-' || str[i] == '+') {str[i++] == '-' ? negative = true : negative = false;}    while(i < str.size()) {        if(str[i] >= '0' && str[i] <= '9') {            res = res * 10 + (str[i] - '0');            if(res > INT_MAX) return negative ? INT_MIN : INT_MAX;        } else {break;}        i++;    }    return negative ? -1 * res : res;    }


0 0
原创粉丝点击