[LeetCode] NO.7 Reverse Integer

[题目] 

Reverse digits of an integer.

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

 

[题目解析] 思路比较直接,这里要特别注意的是负数和整数越界的情况。

    public static int reverse(int x) {
        boolean isPos = x > 0; //判断是否为正数标识
        if(!isPos) x = x * -1;//如果为负数,先乘以-1 转化成正数
        int ans = 0;
        while(x > 0){
            if( (ans) > (Integer.MAX_VALUE)/10) return 0;//overflows 返回0
            ans = ans * 10 + x % 10; //x%10为取得当前位上的数字,每次用累加的和乘10,原来个位上的数字正好变成最高位,其他位类推
            x /=10; //每次循环除以10
        }
        return isPos? ans: -1*ans; //若为正数直接返回,为负数则要乘以-1,因为ans算出来是正数
    }

注意判断是否溢出的时候,是判断的Integer.Max_VALUE/10, 这是为了保险起见,因为如果不除以10,在计算的时候会出现溢出的情况。

posted @ 2016-08-25 15:17  三刀  阅读(190)  评论(0编辑  收藏  举报