`

Reverse Integer

阅读更多
Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

这是一道比较简单的题目,但也是面试中容易考到的题目,主要考察我们对于整数越界时的处理,我们要根据题目的要求进行不同的处理。这个题目要求我们返回一个int型的整数,因此我们对于越界的数统一返回一个合理的整数。代码如下:
public class Solution {
    public int reverse(int x) {
        int result = 0;
        int abs = Math.abs(x);
        while(abs != 0) {
            if(result > (Integer.MAX_VALUE - abs % 10) / 10)
                return 0;
            result = result * 10 + abs % 10;
            abs /= 10;
        }
        return x < 0 ? -result : result;
    }
}


其中对于result > (Integer.MAX_VALUE - abs % 10) / 10的判断就是对越界整数的处理,这里我们统一返回0。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics