Leetcode: 7. Reverse Integer(JAVA)

【 Problem Description 】

Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.

[thinking]
This problem seems simple, but there are more pits.
Integer inversion is a simple problem, but overflow needs to be dealt with.
Save the result as a long, returning 0 if it is greater than the integer maximum or less than the negative minimum
[code]

public class Solution {
    public int reverse(int x) {
		if (x == 0) {
			return 0;
		}

		int sign = 1;
		if (x < 0) {
			sign = -1;
		}
		long result = 0;
		long t = Math.abs((long) x);

		while (t != 0) {
			result = result * 10 + t % 10;
			;
			t /= 10;
		}

		if ((sign == 1 && result > Integer.MAX_VALUE)
				|| (sign == -1 && sign * result < Integer.MIN_VALUE)) {
			return 0;
		}
		return sign * (int) result;
    }
}

Read More: