【24.整数反转】

0 阅读1分钟

题目

给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。

如果反转后整数超过 32 位的有符号整数的范围 [−231,  231 − 1] ,就返回 0。

假设环境不允许存储 64 位整数(有符号或无符号)。

示例 1:

输入: x = 123
输出: 321

示例 2:

输入: x = -123
输出: -321

题解

方式一:栈

复杂度:不会算

public int reverse(int x) {
    int ans = 0;
    while (x != 0) {
        int digit = x % 10; // 在 Java 中,对于 int 类型的变量 x 和 y,x % y 的结果的符号与 x 相同
        // 因为ans每次要执行 * 10 + digit的操作,所以执行前判断是否溢出
        if (ans < Integer.MIN_VALUE / 10 || (ans == Integer.MIN_VALUE && digit < Integer.MIN_VALUE % 10)) {
            return 0;
        }
        if (ans > Integer.MAX_VALUE / 10 || (ans == Integer.MIN_VALUE && digit > Integer.MAX_VALUE % 10)) {
            return 0;
        }
        x /= 10;
        ans = ans * 10 + digit;
    }
    return ans;
}

总结

数据结构:
算法:溢出判断