整数反转
题目:
给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。
如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1] ,就返回 0。
假设环境不允许存储 64 位整数(有符号或无符号)。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-integer
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处
//在不考虑溢出的情况下,以下代码逻辑简单易理解
class Solution { public int reverse(int x) { int y = 0; while (x != 0) { y = y * 10 + x % 10; x = x / 10; } return y; } }
下面这段摘自讨论区一位大佬的讲解,有考虑到溢出
class Solution { public int reverse(int x) { int ans = 0;//结果 while (x != 0) { int pop = x % 10; if (ans > Integer.MAX_VALUE / 10 || (ans == Integer.MAX_VALUE / 10 && pop > 7)) return 0; if (ans < Integer.MIN_VALUE / 10 || (ans == Integer.MIN_VALUE / 10 && pop < -8)) return 0; ans = ans * 10 + pop; x /= 10; } return ans; } } 作者:guanpengchn 链接:https://leetcode-cn.com/problems/reverse-integer/solution/hua-jie-suan-fa-7-zheng-shu-fan-zhuan-by-guanpengc/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

浙公网安备 33010602011771号