首页 > 其他 > 详细

String to Integer (atoi)

时间:2015-05-29 06:11:35      阅读:292      评论:0      收藏:0      [点我收藏+]

极值问题

public class Solution {
    public int myAtoi(String str) {
        // 要考虑清楚极值问题
        if(str==null || str.length()==0) return 0;
        int i=0, res=0;
        str = str.trim();
        int sn=1;
        if(str.charAt(0)==‘-‘){
            sn =-1;
            i++;
        }else if(str.charAt(0)==‘+‘){
            i++;
        }
        while(i<str.length()&& str.charAt(i)>=‘0‘ &&str.charAt(i)<=‘9‘ ){
            if(res>Integer.MAX_VALUE/10 ||( res==Integer.MAX_VALUE/10 && str.charAt(i)-‘0‘>Integer.MAX_VALUE%10)){ //不能写成res*10...
                return sn==1?Integer.MAX_VALUE:Integer.MIN_VALUE;
            }else{
                res = res*10 + str.charAt(i)-‘0‘;
                i++;
            }
            
        }
        return sn <0? -res : res;
    }
}

 

String to Integer (atoi)

原文:http://www.cnblogs.com/jiajiaxingxing/p/4537515.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!