Problem Description:
Reverse digits of an integer.
EXAMPLE1:X = 123, return 321
example2:x = -123, return-321
Analysis: the output of an integer in reverse order, you need to determine whether out of bounds. Integer.max_value,integer.min_value, because a positive and negative cross-boundary judgment is to be made, a negative number is converted to an integer .
Code
Public intReverseintx) {intRET = 0; intDigit = 0; BooleanNeg_flag =false; if(X < 0) {Neg_flag=true; X=-1 * x;//Covert to ABS (x), and record the symbol of negative or positive. } while(x! = 0) {digit= x% 10;//get the last digit of x, get the number at the end of X//if ret overflows? if(ret! = 0) {//must follow this pattern to check if((integer.max_value-digit)/RET < 10 ) return0; if(Neg_flag = =true) { if( -10 < (integer.min_value + digit)/ret)//-(ret * + digit) < Integer.min_value//If we convert the number to ABS, we need to compare it in negative form with Integer.min_value return0; }} RET= RET * 10 +Digit; X= X/10;//chop off the last digit of x, cut the end number of x } if(Neg_flag = =true) ret=-1 *ret; returnret; }
Reverse Integer Leetcode Java