|
| 1 | +#!usr/bin/env python |
| 2 | +# -*- coding:utf-8 -*- |
| 3 | +''' |
| 4 | +Reverse digits of an integer. |
| 5 | + |
| 6 | +Example1: x = 123, return 321 |
| 7 | +Example2: x = -123, return -321 |
| 8 | + |
| 9 | +Here are some good questions to ask before coding. Bonus points for you if you have already thought through this! |
| 10 | + |
| 11 | +If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100. |
| 12 | + |
| 13 | +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? |
| 14 | + |
| 15 | +For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. |
| 16 | +''' |
| 17 | + |
| 18 | + |
| 19 | +class Solution(object): |
| 20 | + def reverse(self, x): |
| 21 | + """ |
| 22 | + :type x: int |
| 23 | + :rtype: int |
| 24 | + """ |
| 25 | + # Consider positive and negative situation |
| 26 | + flag = 0 |
| 27 | + if x < 0: |
| 28 | + flag = -1 |
| 29 | + if x > 0: |
| 30 | + flag = 1 |
| 31 | + x *= flag |
| 32 | + result = 0 |
| 33 | + while x: |
| 34 | + result = result * 10 + x % 10 |
| 35 | + x //= 10 |
| 36 | + if result > 2 ** 32 - 1: #2的32次方 |
| 37 | + return 0 |
| 38 | + else: |
| 39 | + return result*flag |
| 40 | + |
| 41 | + |
| 42 | +if __name__ == "__main__": |
| 43 | + assert Solution().reverse(654300) == 3456 |
| 44 | + assert Solution().reverse(-321) == -123 |
| 45 | + assert Solution().reverse(21474836470) == 0 |
| 46 | + |
| 47 | + |
| 48 | + |
| 49 | + |
| 50 | + |
| 51 | + |
| 52 | + |
| 53 | + |
0 commit comments