Reverse A integer is a very common task we need to understand for being a good programmer. It's very easy at some aspects, however, it also needs a prudent mind to understand all corner cases it may encounter.
The basic idea of reversing a number are to use mod "%" and divID "/" collectedly.
1. Get the last digit of a number (ten as base, decimal numeral system)
digit = num% 10
2. Chop off the last digit of a number
Num_remain = NUM/10
The basic idea is:
int ret = 0 while (num_remain! = 0 ) {
= num% 10
= RET * + digit;
= Num_remain/10;}
However, there is a big pitfall at here. The problem is, the ret_num could exceed the max number a integer could represent in Java. What's more, if the NUM is a negative number, the symbol of the ret_num could isn't be predicted. We need to add some fix for the basic structure above.
1. Convert the number into positive form before reversion.
if (Num < 0= num *-1;
true ; }
2. Add proper mechanism to check possible overflow. (Note:the Ret_num is positive now!)
if (ret! = 0) { if (integer.max_value-digit)/ret < 10) return 0; if (Neg_flag = = true if ( -10 < (integer.min_value + digit)/ ret) return 0; }} RET = ret * + digit;
The reason is: (when overflow happens)
IFF Neg_flag = Fase, (note:the ret_num is positive now!)
RET * + digit > Integer.max_value <=> (integer.max_value-digit)/RET < 10
IFF Neg_flag = True,
-(RET * + digit) < Integer.min_value <=> -10 < (integer.min_value + digit)/RET
Questions:
Reverse digits of an integer.
EXAMPLE1:X = 123, return 321
example2:x = -123, return-321
My Answer:
//Take care of overflow//both mod and divid can have positive/negative symbols Public classSolution {//Watch out for all corner cases!!! 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 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 } if(Neg_flag = =true&& ret > 0) ret=-1 *ret; returnret; }}
[Leetcode#7] Reverse Integer