给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。
如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1] ,就返回 0。
假设环境不允许存储 64 位整数(有符号或无符号)。
示例 1:
输入:x = 123
输出:321
示例 2:
输入:x = -123
输出:-321
示例 3:
输入:x = 120
输出:21
示例 4:
输入:x = 0
输出:0
解题思路
1、先判断是正数还是负数,正数取原值,否则取相反数,记为n
2、循环以下过程:取n / 10 的整数部分a和余数部分b,res = res * 10 +余数b。更新n为a,循环直到n为0
3、将符号添上
class Solution {
public int reverse(int x) {
int n;
if(x>0){
n = x;
}else {
n = 0-x;
}
int res = 0;
int tmp;
while(n>0){
tmp = n % 10;
n = n / 10;
if(res>Math.pow(2, 31)/10){
return 0;
}
res = res * 10 + tmp;
}
return x >= 0? res : - res;
}
}
python实现
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x > 0:
n = x
else:
n = -x
res = 0
while n > 0:
tmp = n % 10
n = n / 10
if(res > (1 << 31) / 10):
return 0
res = res * 10 + tmp
return res if x >= 0 else - res