分类:Math
考察知识点:Math
最优解时间复杂度:**O(n) **
7.Reverse Integer
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 store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
代码:
我的方法:
class Solution:
def reverse(self, x):
if x<-2**31 or x>2**31-1 or x==0:
return 0
res=0
s=1
if x<0:
s=-1
x=-x
while x:
res=(res+(x%10))*10
print(res)
x=x//10
res=res//10*s
if res<-2**31 or res>2**31-1:
return 0
return res
讨论:
1.简单哦