Reverse Integer

来源:互联网 发布:视上眼镜淘宝 编辑:程序博客网 时间:2024/05/21 06:48

1.题目

将一个整数中的数字进行颠倒,当颠倒后的整数溢出时,返回 0 (标记为 32 位整数)。

给定 x = 123,返回 321

给定 x = -123,返回 -321

2.算法

这道题是数值计算的题目,遇到这样的题,我们先把数值取绝对值num,我们先取对num余10,得到个位i1,在乘10,并循环,直到num==0;这道题需要在两个地方检测边界条件

1,当n为-Integer.MIN_VALUE时,反转会越界

2.每次循环时,我们也要检测是否越界

    public int reverseInteger(int n) {        // Write your code here        if (n == Integer.MIN_VALUE) {            return 0;        }        int num = Math.abs(n);        int res = 0;        while (num != 0) {            if (res > (Integer.MAX_VALUE - num % 10) / 10) { //检测下次循环是否越界                return 0;            }            res = res * 10 + num % 10;            num = num / 10;        }        return n > 0 ? res : -res; //检测元数是正是负    }

    def reverseInteger(self, n):        # Write your code here        if n == 0:            return 0        flg = 1        res = 0        if n < 0:            flg, n = -1, -n        while n > 0:            res = res * 10 + n % 10            n /= 10        res *= flg        if res < -(1 << 31) or res > ((1 << 31) - 1):            return 0        return res


0 0