实现将字符串转换成整数atoi(牛客网)

思路:将所得到的字符串进行处理,将其处理成非法和合法
例如”++1234”,”–1234”,”+-1234”这些都是不合法的,因为常规来讲没有人会这样写一个数,所以我们就处理”-1234”,”+1234”,” 1234”此种类型的,

具体实现代码

#include<string>
#include<iostream>
using namespace std;
int strtoint(string str){
    if (str.size() == 0){
        return 0;
    }
    long long num = 0;
    int s = 1;
    if (str[0] == '-'){
        s = -1;
    }
    for (int i =(str[0]=='-'||str[0]=='+')?1:0; i < str.size(); i++){
        if ((str[i] >= '0'&&str[i] <= '9')){
            num = num * 10 + str[i] - '0';
        }
        else if (str[i] == ' '){
            continue;
        }
        else{
            return 0;
        }
    }
    return num*s;
}
int main(){
    string str = "  0234";
    int num=strtoint(str);
    cout << num << endl;
    system("pause");
    return 0;
}
**************************************************************
**************************************************************
#include<string>
#include<iostream>
using namespace std;
int strtoint(string str) {
    if(str.size() == 0){
        return 0;
    }
    int result = 0;
    if (str[0]== '-' || str[0] == '+') {
        for (int i = 1; i < str.length(); i++) {
            if (str[i] < '0' || str[i] > '9') {
                return 0;
            }
            result = result * 10 + (str[i] - '0');
        }
        if (str[0] == '-') {
            result = 0 - result;
        }
    }
    else {
        for (int i = 0; i < str.length(); i++) {

            if (str[i] == ' '){
                continue;
            }
            else if (str[i] >= '0'&&str[i] <= '9'){
                result = result * 10 + (str[i] - '0');
            }
            else
                return 0;
        }
    }
    return result;
}

int main(){
    string str = "-0234";
    int num=strtoint(str);
    cout << num << endl;
    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/cx2479750196/article/details/80485270