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: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
解法1:字符串,反转字符串,str(x)[::-1]
class Solution:
def reverse(self, x):
"""
type:x:int
rtype:int
"""
if(x<0):
res=-1 *int(str(-x)[::-1])
else:
res=int(str(x)[::-1])
if res>2147483647 or res<-2147483648:
res=0
return res
解法二:取余,Python中,3/4=0.75 3//4=0
class Solution:
def reverse(self, x):
"""
type:x:int
rtype:int
"""
res=0
ispositive=True
if(x<0):
ispositive=False
x=abs(x)
while x>0:
res=res*10+x%10
x //= 10
if(ispositive==False):
res = -1 * res
if res>2147483647 or res<-2147483648:
return 0
return res