atoi

将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0

输入描述:
输入一个字符串,包括数字字母符号,可以为空
输出描述:
如果是合法的数值表达则返回该数字,否则返回0

输入
+2147483647
1a33
输出
2147483647
0

我的代码

class Solution {
public:
    bool isnum(char ch){
        if(ch <= '9' && ch >= '0') return true;
        return false;
    }
    bool isfuhao(char ch) {
        if(ch == '+' || ch == '-') return true;
        return false;
    }
    int tonum(char ch) {
        return ch - '0';
    }
    int StrToInt(string str) {
        if(str.size() == 0) return 0;
        if(!isnum(str[0]) && !isfuhao(str[0]) || str[0] =='0') return 0;
        if(isfuhao(str[0]) &&  str.size() == 1) return 0;
        if(isfuhao(str[0]) &&  str[1] =='0') return 0;
        int flag = 1;
        if(str[0] == '-') flag = 0;
        queue<int> q;
        if(isnum(str[0]) && str[0] != '0') q.push(tonum(str[0]));
        for(int i = 1; i < str.size(); i++){
            if(!isnum(str[i])) return 0;
            q.push(tonum(str[i]));
        }
        int count = 0;
        while(!q.empty()) {
            count = count * 10 + q.front();
            q.pop();
        }
        if(flag) return count;
        else return count*(-1);
    }
};

官方解答

链接:https://www.nowcoder.com/questionTerminal/1277c681251b4372bdef344468e4f26e?answerType=1&f=discussion
来源:牛客网

class Solution {
public:
    int StrToInt(string str) {
        const int len = str.length();
        if (len == 0) return 0;
        int i = 0;
        while (i < len && str[i] == ' ') { ++i; } // 排除开头的空格
        if (i == len) return 0;
        if (!isdigit(str[i]) && str[i] != '+' && str[i] != '-') return 0;
        bool neg = str[i]=='-' ? true : false;
        i = isdigit(str[i]) ? i : i+1;
        long long ans = 0L;

        while (i < len && isdigit(str[i])) {
            ans = ans * 10 + (str[i++]-'0');

            if (!neg && ans > INT_MAX) {
                ans = INT_MAX;
                break;
            }
            if (neg && ans > 1L + INT_MAX) {
                ans = 1L + INT_MAX;
                break;
            }
        }
        if (i != len) return 0; // 不要此处,就是atoi()库函数的实现
        return !neg ? static_cast<int>(ans) : static_cast<int>(-ans);
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值