首页 > 其他 > 详细

Reverse Integer

时间:2015-05-29 06:08:55      阅读:258      评论:0      收藏:0      [点我收藏+]

这道题不考虑越界问题的话,最粗暴的解法

public class Solution {
    public int reverse(int x) {
        int rev =0;
        while(x!=0){
            rev =rev*10+x%10;
            x /=10;
        }
        return rev;
    }
}

但是很显然,当rev> Integer.MAX_VALUE 的时候要返回0

修改http://blog.csdn.net/linhuanmars/article/details/20024837

public class Solution {
    public int reverse(int x) {
        if(x==Integer.MIN_VALUE) return 0;
        int x1= Math.abs(x);
        int rev =0;
        while(x1!=0){
            if(rev>(Integer.MAX_VALUE-x1%10)/10) 
                return 0;
            rev =rev*10+x1%10;
            x1 /=10;
        }
        return x>0?rev:-rev;
    }
}

 

Reverse Integer

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

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