Problem
Problem page: https://leetcode.com/problems/reverse-integer/
Topics: Math
Difficulty: Easy
Similar problems: (E) String to Integer (atoi)
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321Have 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.
Analysis
"Reverse" a number. The main thing to watch out for is how to handle negative numbers. Overflow is an important detail that's easy to miss in interview problems involving arithmetic. I'm using Python here, so handling input values outside the int range isn't a problem. But the problem asks me to return 0 on int overflow, so I need to check the input and watch for overflow at each step as I reverse the number.
There's also a Python gotcha. At first I just used sys.maxint as the maximum int value. That gave me the right result on 64-bit win7, but I got the wrong result when I ran it on leetcode. I found out it was because sys.maxint is 32-bit on windows and 64-bit on linux. The official docs say "This is at least 2**31-1".
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-reverse-integer/
