String to Integer (atoi)

String to Integer (atoi) – leetcode
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
将字符串转为整型,模仿系统的atoi函数
注意:字符串输入的格式:
字符串可能的输入:
(1)剔除字符串前空格
(2)数字前最多允许1个”+”或”-“,出现多个时返回0;
(3)数字中出现不为数字的符号时即认为数字结束,比如” 123”, “134ab”,”134-5”,”134 65”都判定为134;“abc123”,“–123”,“.123”等都判定为0。
(4)数字大于INT_MAX(2^31-1 = 2147483647)时,返回INT_MAX,小于INT_MIN(-2^31 = -2147483648)时,返回INT_MIN

代码:

class Solution {
public:
    int myAtoi(string str) {
        //字符串长度
        int lenStr = str.size();
        //符号位
        int symbol = 1;
        //转换的整型结果
        long result = 0;

        //去除字符串前置的空格
        int i = 0;
        while( i<lenStr && str[i] == ' ') ++i;

        //判断字符的正负
        if (str[i] == '+' || str[i] == '-'){
            if (str[i] == '-') symbol = -1;
            ++i;
        }

        //转换为int型
        for (int j = i; j<lenStr; ++j){
            if (str[j] >= '0' && str[j] <= '9'){//判断字符是否在0~9之间
                result = result * 10 + (str[j] - '0');//转换为整型
                if (symbol == 1 && result > 2147483647) return 2147483647;//判断正数是否越界
                if (symbol == -1 && result > 2147483648) return -2147483648;//判断负数是否越界
            } else break;
        }
        return (int)(result * symbol);

    }
};
不积跬步,无以至千里;不积小流,无以成江海。
原文地址:https://www.cnblogs.com/xiaocai-ios/p/7779788.html