反转整数123变为321,-123变为-321
注意:在32位整数范围内,并且001要成为1
假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−2^31, 2^31 − 1]。根据这个假设,如果反转后的整数溢出,则返回 0。
该题最主要的是,判断越界问题
https://leetcode-cn.com/problems/reverse-integer/solution/
要在没有辅助堆栈 / 数组的帮助下 “弹出” 和 “推入” 数字,我们可以使用数学方法。
//pop operation:
pop = x % 10;
x /= 10;
//push operation:
temp = rev * 10 + pop;
rev = temp;
但是,这种方法很危险,因为当 temp=rev⋅10+poptemp=rev⋅10+pop\text{temp} = \text{rev} \cdot 10 + \text{pop} 时会导致溢出。
幸运的是,事先检查这个语句是否会导致溢出很容易。
因为:2^31 -1= 2147483647 -2^31 = -2147483648
class Solution {
public int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
}
}
python没有溢出问题,处理这题投机取巧
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x < 0:
result = -int(str(-x)[::-1]) # 字符串倒序输出
else:
result = int(str(x)[::-1])
if result < -2147483648 or result > 2147483647:
return 0
return result
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有