题解 | 把字符串转换成整数(atoi)

把字符串转换成整数(atoi)

https://www.nowcoder.com/practice/d11471c3bf2d40f38b66bb12785df47f

#include <climits>
class Solution {
public:
    //遍历处理每一位,跳过前导0,判断符号,得到数字,遇得到符号终止
    int StrToInt(string s) {
        int n=s.length();
        int index = 0;

        while(index < n && s[index] == ' '){  //去掉前导0
            index++;
        }

        if(index == n){
            return 0;
        }

        int ans=0;
        int sign = 1;
        if(s[index] == '+'){
            index++;
        }else if(s[index] == '-'){
            index++;
            sign = -1;
        }

        if(index == n){
            return 0;
        }

        while(index < n){
            char c = s[index];

            if(c < '0' || c > '9'){
                return ans;
            }

            if(ans > INT_MAX/10 || ( ans==INT_MAX/10 && (c-'0')>=7 )){
                return INT_MAX;
            }

            if(ans < INT_MIN/10 || ( ans==INT_MIN/10 && (c-'0')>=8 )){
                return INT_MIN;
            }

            ans = ans*10 + sign*(c-'0');
            index++;
        }

        return ans;
    }
};

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务