[leetcode-8]String to Integer (atoi)(java)

本文介绍了一种将字符串转换为整数的有效方法。重点讨论了输入情况的处理,包括正负号、非数字字符及可能的整数溢出问题,并提供了一个具体的Java代码示例。

问题描述:
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.

分析:首先,先对字符串进行一次过滤,将开头的空格去掉。然后在查找之后的,当遇到+-时后面一定要求是数字,也即不能是++或者+-或者-+或者–等情况。此外,更重要的一点是注意溢出现象。特别的当sum*10时发生溢出不好判断,因此,我设置了sum的阈值。当sum>这个阈值时,肯定会发生溢出。此时,再单独处理。

代码如下:404ms

    public int myAtoi(String str) {
        char tmp;
        int sum = 0;
        int i;
        boolean minus = false;
        boolean requireNumber = false;
        boolean overflow = false;
        //clear the space
        for(i = 0;i<str.length();i++){
            if((tmp=str.charAt(i))!=' ')
                break;
        }   
        for(;i<str.length();i++){
            if((tmp=str.charAt(i))=='+'){
                if(requireNumber)
                    break;
                requireNumber = true;
            }
            else if(tmp=='-'){
                if(requireNumber)
                    break;
                requireNumber = true;
                minus = true;
            }
            else if(tmp>='0'&&tmp<='9'){
                if(sum>Integer.MAX_VALUE/10){
                    sum = -1;
                }else
                    sum = sum*10+tmp-'0';
                if(sum<0){
                    sum = Integer.MAX_VALUE;
                    overflow = true;
                }
            }else {
                break;
            }
        }
        if(overflow&&minus)
            return sum+1;
        else if(overflow)
            return sum;
        return minus?-sum:sum;
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值