Reverse Integer

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

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;
    }
}

 

posted @ 2015-05-29 03:10  世界到处都是小星星  阅读(110)  评论(0编辑  收藏  举报