8. String to Integer (atoi)

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.

这道题还是对于Integer的处理,在Reverse Integer这道题中我有提到,这种题的考察重点并不在于问题本身,而是要注意corner case的处理,整数一般有两点,一个是正负符号问题,另一个是整数越界问题。思路比较简单,就是先去掉多余的空格字符,然后读符号(注意正负号都有可能,也有可能没有符号),接下来按顺序读数字,结束条件有三种情况:(1)异常字符出现(按照C语言的标准是把异常字符起的后面全部截去,保留前面的部分作为结果);(2)数字越界(返回最接近的整数);(3)字符串结束。代码如下:
来自: http://blog.youkuaiyun.com/linhuanmars/article/details/21145129

public int myAtoi(String str) {
    if(str == null) return 0;
    if(str.isEmpty()) return 0;
       char[] s2ch = str.toCharArray();
       int len = s2ch.length;
       int res = 0;
       boolean positive = true;
       int i = 0;
       while(s2ch[i] == ' '){
           i++;
       }

       if(s2ch[i] != '+'){
           if(s2ch[i] == '-') 
               positive = false;
           else if(s2ch[i] < '0' || s2ch[i] > '9') 
                   return 0;
               else 
                   res = s2ch[i] - '0';
       }
       i++;

       for(;i < len;i++){
        if(s2ch[i] < '0' || s2ch[i] > '9') break;
        int digit = s2ch[i] - '0';
        if(!positive && res>-((Integer.MIN_VALUE+digit)/10))  
               return Integer.MIN_VALUE;  
           else if(positive && res>(Integer.MAX_VALUE-digit)/10)  
               return Integer.MAX_VALUE;  
        res = 10*res + digit;
       }

    return positive ? res : -res;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值