Reverse Integer leetcode -- how to handle overflow

algorithm, integer, java, reverse

Solution

There's no need for any data type other than int. Just make sure when there's an operation that increases a number, reversing the operation should give you the previous number. Otherwise, there's overflow.

public int reverse(int x) {
    int y = 0;

    while(x != 0) {
        int yy = y*10 + x%10;

        if ((yy - x%10)/10 != y) return 0;
        else y = yy;

        x = x/10;   
    }
    return y;
}

Problem

The problem is: Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 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? Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter). The solution from the website I search is: ``` public class Solution { public static int reverse(int x) { int ret = 0; boolean zero = false; while (!zero) { ret = ret * 10 + (x % 10); x /= 10; if(x == 0){ zero = true; } } return ret; } public static void main(String[] args) { int s = 1000000003; System.out.println(reverse(s)); } } ``` However when `s = 1000000003`, the console prints `-1294967295` instead of `3000000001`. So this solution still does not solve the overflow problem if we cannot use exception. Any help here?(Although there is a hint: add an extra parameter, I still cannot figure out what parameter I should add)

Original source

Related problems