7.反转整数
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
解答:
法1:
#反转整数的时候要注意是否会溢出
sig = -1 if x < 0 else 1
#x = int(str(abs(x))[::-1])*sig
#if x < -2**31 or x > 2**31-1:
# return 0
#else:
# return x
x = abs(x)
y = 0
while x > 0:
y = y*10 + x % 10
x = x // 10
y = y * sig
if y < -2**31 or y > 2**31-1:
return 0
else:
return y
法2:
sign = -1 if x < 0 else 1
y = int(str(abs(x))[::-1])*sign
if y < -2**31 or y > 2 **31-1:
return 0
else:
return y
本文介绍了一种用于反转32位有符号整数的方法,并提供了两种不同的实现方案。通过对输入整数的数字进行反转操作,该算法能够正确处理正数、负数以及包含前导零的情况。同时,它还考虑了反转后的整数是否超出32位有符号整数范围的问题。
461

被折叠的 条评论
为什么被折叠?



