把字符串转换成整数

把字符串转换成整数

题目描述

将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。

改了又改, 有空格滤除, 溢出判断, 感觉还不是很完整

class Solution {
public:
    int StrToInt(string str) {
        long long  res = 0;
        int pCt = 0;
        int len = str.length();
        int flag = 1;
        for (const auto ch : str) {
            if (ch == ' ') pCt++;
            else           break;
        }
        if ((len > 0) && (str[pCt] == '+')) {
            pCt++;
        }
        if ((len > 0) && (str[pCt] == '-')) {
            flag = -1;
            pCt++;
        }
        while (pCt < len) {
            int temp = str[pCt] - '0';
            if ((0 > temp) || (9 < temp)) {
                return 0;
            }
            res = res*10 + temp;
            if (((flag > 0) && (res > INT_MAX))
                 || ((flag < 0) && (-res < INT_MIN)))
                return 0;
            pCt++;
        }
        return flag*res;
    }
};

初版, 没过滤数字前面空格, 没有溢出处理, 牛客可通过:(

class Solution {
public:
    int StrToInt(string str) {
        if (str.length() < 0) {
            return 0;
        }
        int res = 0;
        int pos = 10;
        // 判断正负
        if (str[0] == '-') {
            pos = -1;
        }
        else if (str[0] == '+') {
            pos = 1;
        }
        else if (str[0] - '0' < 0 || str[0] - '0' > 9) {
            return 0;
        }

        if (pos != 10) {
            for (int i = 1; i < str.length(); i++) {
                int temp = str[i] - '0';
                if (temp < 0 || temp > 9) {
                    return 0;
                }
                res = res * 10 + temp;
            }
            return pos*res;
        }
        else {
            for (int i = 0; i < str.length(); i++) {
                int temp = str[i] - '0';
                if (temp < 0 || temp > 9) {
                    return 0;
                }
                res = res * 10 + temp;
            }
            return res;
        }


    }
};
原文地址:https://www.cnblogs.com/hesper/p/10534120.html