class Solution {
public:
int reverse(int x) {
int res = 0;
while(x != 0){
int pop = x % 10;
x /= 10;
if(res > INT_MAX / 10 || (res == INTMAX_MAX / 10 && pop > 7)) return 0;
if(res < INT_MIN / 10 || (res == INT_MIN / 10 && pop < -8)) return 0;
res = res * 10 + pop;
}
return res;
}
};
python
#
#
# @param x int整型
# @return int整型
#
class Solution:
def reverse(self , x ):
# write code here
s = str(x)
if s[0] != '-':
s = s[::-1]
if int(s) < -pow(2, 31) or int(s) > pow(2, 31)-1:
return 0
else:
return int(s)
else:
s = s[1:]
s = s[::-1]
if -int(s) < -pow(2, 31) or -int(s) > pow(2, 31)-1:
return 0
else:
return -int(s)