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)