Question: http://oj.leetcode.com/problems/reverse-integer/

Question Name: Reverse Integer

Python is an overwhelmingly excellent choice to solve this question, right? Firstly, this is a non-recursive solution:

1 2 3 4 5 | class Solution: # @return an integer def reverse(self, x): if x < 0: return int(str(x)[1:][::-1])*-1 else: return int(str(x)[::-1]) |

We also provide a recursive solution as following:

1 2 3 4 5 6 7 8 9 10 11 | class Solution: # @return an integer def _reverse_helper(self, x): if -10 < x < 10: return x, 1 else: rest, digits = self._reverse_helper(x / 10) return x % 10 * (10 ** digits) + rest, digits + 1 def reverse(self, x): if x < 0: return self._reverse_helper(-x)[0] * -1 else: return self._reverse_helper(x)[0] |

**UPDATE:** challenge updated to test the overflow behavior.

1 2 3 4 5 6 7 8 9 10 11 12 13 | class Solution: # @return an integer def _reverse_helper(self, x): if -10 < x < 10: return x, 1 else: rest, digits = self._reverse_helper(x / 10) return x % 10 * (10 ** digits) + rest, digits + 1 def reverse(self, x): if x < 0: result = self._reverse_helper(-x)[0] * -1 else: result = self._reverse_helper(x)[0] if -2147483648L <= result <= 2147483647L: return result else: return 0 |

The problem has been updated such that the overflow cases should be considered:

”

Update (2014-11-10):

Test cases had been added to test the overflow behavior.

”

An updated solution would be:

Thanks for letting me know!