【done】【难点】剑指offer——面试题49:把字符串转换成整数

力扣,https://leetcode.cn/problems/ba-zi-fu-chuan-zhuan-huan-cheng-zheng-shu-lcof/description/
在这里插入图片描述在这里插入图片描述

class Solution { 
    public int myAtoi(String str) { // int max = 2147483647,int min = -2147483648
        if (str.length() == 0) {
            return 0;
        }
        int i = 0, length = str.length(), sign = 1, res = 0;
        while (str.charAt(i) == ' ') {
            ++i;
            if (i == length) {
                return 0;
            }
        }
        if (str.charAt(i) == '-') {
            sign = -1;
            ++i;
        } else if (str.charAt(i) == '+') {
            ++i;
        }
        int boundary = Integer.MAX_VALUE / 10;
        for (int j = i; j < length; ++j) {
            if (str.charAt(j) < '0' || str.charAt(j) > '9') {
                break;
            }
            int curDigit = str.charAt(j) - '0';
            if (res > boundary || (res == boundary && curDigit > 7)) {
                return sign == -1 ? Integer.MIN_VALUE : Integer.MAX_VALUE;
            }

            res = res * 10 + curDigit;
        }

        return sign * res;
    }
}

##Solution1:
代码写的啰嗦,但思路清晰。。LeetCode上有相似的题目并考虑了溢出,可以参考LeetCode8答案

class Solution { //题目没有考虑到溢出的情况,不是很完美呀~但在牛客网上也能AC了~
public:
    int StrToInt(string str) { //1.去掉首尾空格;2.首字符只能是+、-或数字(若是其他字符,return 0;),并用sign标记;3.若首位非正负号,则全部字符应在‘0’-‘9’之间
        if (str.size() == 0) //字符串为空
            return 0;
        string str_copy = str.substr(str.find_first_not_of(' ')); //删掉头部空格
        str_copy = str_copy.erase(str.find_last_not_of(' ') + 1); //删掉尾部空格
        int sign = 1;
        if (str_copy[0] == '-') {
            sign = -1;
            str_copy = str_copy.erase(0, 1);//删掉符号字符
            if (str_copy.size() == 0)
                return 0;
        } else if(str_copy[0] == '+') {
            sign = 1;
            str_copy = str_copy.erase(0, 1);//删掉符号字符
            if(str_copy.size() == 0)
                return 0;
        } else if(str_copy[0] < '0' || str_copy[0] > '9') { //其它非正负号及数字的字符,return 0;
            return 0;
        }
        //到这一步为止得到的字符串是去掉首位空格及符号位的字符串,若该字符串中含有非数字字符,则return 0;
        //否则转化为数字*sign 返回该值。溢出的情况怎么办,题目没说明。。。
        for (int i = 0; i < str_copy.size(); i++) {
            if(str_copy[i] < '0' || str_copy[i] > '9')
                return 0;
        }
        return sign * my_strtoint(str_copy);
    }
    
    int my_strtoint(string str) {
        int result = 0, base = 1, len_str = 0;
        while(str != "") {
            len_str = str.size();
            result += (str[len_str-1] - '0') * base;
            base *= 10;
            str.erase(len_str - 1);
        }
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值