Leetcode -- String to Integer (atoi)

问题链接:https://oj.leetcode.com/problems/string-to-integer-atoi/

问题描述:Implement atoi to convert a string to an integer.


API: public int atoi(String str)

分析:这连续几题都是数学题,这一题其实也不是很难。难的只是输入的不确定性,因为不能保证输入的合法。但根据spoiler(看链接)给出的提示和限定条件,只需要先用String.trim()去掉前后空格,判断第一位是否正负符号,然后不停往下走,遇到数字就算,遇到其他字符便停。overflow的检测和刚才Reverse Integer是一样的。

下面给出代码:

    public int atoi(String str) {
        str = str.trim();
        int isNeg = 0;
        if(str.length() == 0)
            return 0;
        if(str.charAt(0) == '+')
            isNeg = 1;
        else if(str.charAt(0) == '-')
            isNeg = -1;
        int res = 0;
        int check = 0;
        for(int i = isNeg == 0 ? 0 : 1; i < str.length(); i++){
            char cur_bit = str.charAt(i);
            if(cur_bit <= '9' && cur_bit >= '0'){
                int cur_bit_num = (int)(cur_bit - '0');
                res *= 10;
                res += cur_bit_num * (isNeg == -1 ? -1 : 1);
                if(res / 10 != check){
                    return isNeg == -1 ? Integer.MIN_VALUE : Integer.MAX_VALUE;
                }
                check = res;
            }else{
                break;
            }
        }
        return res;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值