Description
Given a 32-bit signed integer, reverse digits of an integer.
- Example 1:
Input: 123
Output: 321
- Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
public int reverse ( int x ) {
if (x >= 0 && x <= 9){
return x;
}
boolean flag = true;
if (x < 0){
flag = false;
x = - x;
}
long resultInt=0;
while( x > 0 ) {
int y = x % 10;
x = x / 10;
resultInt = resultInt * 10 + y;
}
int answer = ( resultInt > Integer.MAX_VALUE || resultInt < Integer.MIN_VALUE ) ? 0 : (int) resultInt;
if ( flag == true ) {
return answer;
} else {
return (-1) * answer;
}
}
here, we need be careful for answer whether it is bigger than Integer.MAX_VALUE (32 bit int value) or smaller than Integer.MIN_VALUE (32 bit int value).