Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
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.
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
解题思路:
python里面int最大数值0x7FFFFFFF,在考虑溢出的时候需要和这个值进行比较。
-
取模运算可以得到数字的最后一位,/运算会得到移走最后一个数字之外的数字,以此循环
代码如下:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
res = 0
flag = -1 if x<0 else 1
x = x * flag
while(x):
res = res*10 + x%10
x = x/10
if res > 0x7FFFFFFF:
return 0
return res*flag
if __name__ == "__main__":
sol = Solution()
print sol.reverse(123)
print sol.reverse(1000)
print sol.reverse(10001)
print sol.reverse(-123)
print sol.reverse(1000000003)