7. 整数反转
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为
[
−
2
31
,
2
31
−
1
]
[−2^{31}, 2^{31} − 1]
[−231,231−1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
Example
input123output321
input-123output-321
input120output21
Note
无
思路
int转换成字符串类型,然后字符串反转处理一下就好了数学方法——经典小学基础知识(见代码)
代码如下
class Solution:
def reverse(self
, x
: int) -> int:
flag
= 1
if x
<= 0:
flag
= 0
x
= -x
s
= 0
while(x
> 0):
s
= s
*10 + x
%10
x
//= 10
if flag
== 0:
s
= -s
if s
< -2**31 or s
> 2**31 -1:
return 0
else:
return s