Reverse digits of an integer.
Example1: x = 123, return 321
Example1: x = 123, return 321
Example2: x = -123, return -321
这里需要考虑几种边界条件,
1.reverse完后的值大于+-2^32这时返回0
2.负数的处理先按照正数来做,最后再返回负数。
代码如下
class Solution:
# @return an integer
def flip(self,n):
y=0
while n>0:
rest=n%10
n/=10
y=y*10+rest
return y
def reverse(self, x):
n=x
if n>0:
result=self.flip(n)
if result>=2147483648:
return 0
else:
return result
if n<=0:
result=-self.flip(-n)
if result<-2147483648:
return 0
else:
return result