颠倒整数

给定一个 int 整数,将其颠倒。假设只能处理 32 位 int 范围内的整数。根据这个假设,如果颠倒后的结果超过这个范围,则返回 0。

123 -> 321

-123 -> -321

120 -> 21

实现方法较为简单,代码如下:

    public static int reverse(int x) {

        int result = 0;
        while (x != 0) {

            if (result>Integer.MAX_VALUE/10 || result<Integer.MIN_VALUE/10) 
                return 0;
            result = result*10 + x % 10;
            x = x/10;
        }
        return result;
    }

 

if (result>Integer.MAX_VALUE/10 || result<Integer.MIN_VALUE/10)

改行的作用是判断结果是否超出int整数的范围

posted on 2018-04-09 20:05  Deltadeblog  阅读(115)  评论(0编辑  收藏  举报

导航