@TOC

# # 题目描述

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 hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

# # 解题方法

## # 转成字符串

``````class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
n = cmp(x, 0) * int(str(abs(x))[::-1])
return n if n.bit_length() < 32 else 0
``````

``````class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x == 0: return 0
flag = 1
if x < 0:
flag = -1
x = -x
r = int(str(x)[::-1])
if flag == 1 and r <= 2147483647:
return r
elif flag == -1 and -r >= -2147483648:
return -r
return 0
``````

C++版本的代码如下：

``````class Solution {
public:
int reverse(int x) {
if (x == 0) return 0;
int flag = 1;
if (x < 0) flag = -1;
string xs = to_string(x);
long r = stol(string(xs.rbegin(), xs.rend()));
if (flag == 1 && r <= INT_MAX) return r;
if (flag == -1 && -r >= INT_MIN) return -r;
return 0;
}
};
``````

TODO

# # 日期

2018 年 2 月 5 日 2018 年 11 月 30 日 —— 又到了周末 2021 年 8 月 7 日