一、题目
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.
给定一个 32 位有符号整数,将整数中的数字进行反转。
示例 1:
输入: 123 输出: 321
示例 2:
输入: -123 输出: -321
示例 3:
输入: 120 输出: 21
注意:
假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231, 231 − 1]。根据这个假设,如果反转后的整数溢出,则返回 0。
二、代码
利用Python的字符串反转操作来实现对整数的反转,反转后的字符串要重新转换为整数,要注意正负和溢出情况。
def reverse(x):
x = int(str(x)[::-1]) if x >= 0 else - int(str(-x)[::-1])
return x if x < 2147483648 and x >= -2147483648 else 0
if __name__ == '__main__':
x = -123
print(reverse(x))
模十法
复杂度
时间 O(n) 空间 O(1)
思路
通过对数字模十取余得到它的最低位。其实本题考查的是整数相加的溢出处理,检查溢出有这么几种办法:
- 两个正数数相加得到负数,或者两个负数相加得到正数,但某些编译器溢出或优化的方式不一样
- 对于正数,如果最大整数减去一个数小于另一个数,或者对于负数,最小整数减去一个数大于另一个数,则溢出。这是用减法来避免加法的溢出。
- 使用long来保存可能溢出的结果,再与最大/最小整数相比较
public class Solution {
public int reverse(int x) {
long result = 0;
int tmp = Math.abs(x);
while(tmp>0){
result *= 10;
result += tmp % 10;
if(result > Integer.MAX_VALUE){
return 0;
}
tmp /= 10;
}
return (int)(x>=0?result:-result);
}
}
三、参考资料、
[1] 7. Reverse Integer [easy] (Python)