Topic:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return-321
Analysis: At first glance, it seems to be a very simple topic, only need to be the whole number from the lowest to the highest bit in turn, but the key to this problem is how to handle the overflow data. We know that the range of the integer type data is: #define INT_MIN ( -2147483647-1)/* Minimum (Signed) INT value */
#define INT_MAX 2147483647/* Maximum (Signed) INT value */
Also, the overflow judgment here must include both the original data x and the reversal result, all without crossing the boundary. Overflow judgment: (1) 2147483647 is 10 digits, first, when X is 9 digits and below, the original data and reversal data will not cross; (2) Make a special judgment on inversion, reference blog: http://blog.csdn.net/stephen_wong/article /details/28779481 Overflow Judgment Code:
bool Overflow (int x) {if (x/1000000000 = = 0)//x has an absolute value of less than 1000000000, does not cross over {return false;} else if (x = = int_min)//Int_min reversal After the cross-border, it is impossible to take the absolute value as follows (requires a special sentence), directly return True{return true;} x = ABS (x);//x = d463847412- 2147483647. (parameter x, itself is not out of bounds, so D is definitely 1 or 2)//or-d463847412-2147483648. for (int cmp = 463847412; CMP! = 0; cmp/=10, x/=10) {if (X%10 > Cmp%10) {return true;} else if (X%10 < cmp%10) {Retur n false;}} return false;}
AC Code:
Class Solution {Public:int reverse (int x) {if (overflow (x) = = true) {return 0;} int result = 0;while (x!=0) {result = 10*result + x%10;x/= 10;} return result;} Private:bool overflow (int x) {if (x/1000000000 = = 0)//x has an absolute value less than 1000000000, does not cross over {return false;} else if (x = = int_min)//I Nt_min reversal after the cross-border, also can not be taken as follows the absolute value (need a special sentence), directly return True{return true;} x = ABS (x);//x = d463847412- 2147483647. (parameter x, itself is not out of bounds, so D is definitely 1 or 2)//or-d463847412-2147483648. for (int cmp = 463847412; CMP! = 0; cmp/=10, x/=10) {if (X%10 > Cmp%10) {return true;} else if (X%10 < cmp%10) {Retur n false;}} return false;}};
Leetcode (7) Reverse Integer