Thursday, September 10, 2015

Reverse Integer | Leetcode

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.

Update (2014-11-10):

Test cases had been added to test the overflow behavior.

---

Solution: Convert to string and reverse string. Use Integer.parseInt() to check for integer overflow.

We can also solve this without using string conversions. We can extract the first and last digits using division by Math.pow(10, n). That algorithm is a bit more complicated but should be more efficient.
public class Solution {
    public int reverse(int x) {
        if (0 <= x && x < 10) return x;
        
        char[] a = Integer.toString(x).toCharArray();
        for (int first = (a[0] == '-' ? 1 : 0), last = a.length - 1; first < last; first++, last--) {
            char tmp = a[first];
            a[first] = a[last];
            a[last] = tmp;
        }
        
        try {
            return Integer.parseInt(new String(a));
        } catch (Exception e) {
            return 0;
        }
    }
}

No comments: