题目描述
python3解法
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x==0:
return 0
str_x = str(x)
x = ''
if str_x[0] == '-':
x += '-'
x += str_x[len(str_x)-1::-1].lstrip("0").rstrip("-")
x = int(x)
if -2**31<x<2**31-1:
return x
return 0
JavaScript解法
var reverse = function(x) {
var max = Math.pow(2, 31) - 1;
var min = -Math.pow(2, 31);
var y = 0;
while(x !== 0) {
y = 10 * y + x % 10;
x = ~~(x/10);
}
if (y > max) return 0;
if (y < min) return 0;
return y;
};
C++解法
- 解法1:这里需要注意的是,必须将ret定为long类型,不然编译不过,会溢出,其他的按要求即可
class Solution {
public:
int reverse(int x) {
int a = 0;
long ret = 0;
while(x != 0)
{
a = x % 10;
x = x / 10;
ret = ret * 10 + a;
if(ret < INT_MIN || ret > INT_MAX)
return 0;
}
return (int)ret;
}
};
- 解法2
class Solution {
public:
int reverse(int x) {
int rpc = 0;
while(x != 0){
if(rpc > INT32_MAX/10 || (rpc == INT32_MAX/10 && x%10 > 7))
return 0;
if(rpc < INT32_MIN/10 || (rpc == INT32_MIN/10 && x%10 < -8))
return 0;
rpc = rpc*10 + x%10;
x = x/10;
}
return rpc;
}
};