Reverse digits of an integer. Returns 0 when the reversed integer overflows (signed 32-bit integer).
Example
Given x = 123
, return 321
Given x = -123
, return -321
public class Solution {
/**
* @param n the integer to be reversed
* @return the reversed integer
*/
public int reverseInteger(int n) {
boolean neg = n < 0 ? true : false;
if(neg) {//treat with min value first
if(n == Integer.MIN_VALUE) return 0;
else n = -n;
}
int res = 0;
while(n != 0) {
int tmp = n % 10;
if((Integer.MAX_VALUE - tmp) / 10 < res) return 0; //avoid overflows
res = res * 10 + tmp;
n = n / 10;
}
return neg ? -res : res;
}
}