Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Update (2014-11-10):
Test cases had been added to test the overflow behavior.
题意:
倒置一个整数
注意:
保留符号
如果结尾是0,返回值如何
倒置后可能溢出,如何处理:如果溢出,返回0
参考:
http://www.cnblogs.com/CheeseZH/p/4033801.html
http://www.tuicool.com/articles/ZFJf6vF
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
ans=0
if x<0: #符号判断
flag=-1
x=flag*x
else:
flag=1
while x>0: #正数的倒置
ans=ans*10+x%10
x/=10
if ans>2147483647: #溢出判断
return 0
return flag*ans #带上符号