Title Description
Gives a 32-bit signed integer, you need this integer number on each inverted.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Thinking
We can build a single digit integer reversed once. In doing so, we can check in advance whether another original integer additional digit will cause an overflow.
key point
Pop and push into digital
Pop: int X = POP 10% ;
Push: ANS ANS = + 10 * POP;
x /= 10;
Check before overflow
- If you do not consider this question overflow problem it is very simple. There are two ideas to solve the overflow problem, the first idea is to convert a string by adding try catch to address the way, the second idea is through mathematical calculations to solve.
- Due to the lower string conversion efficiency and use more library function, so the program does not consider the problem-solving method, but to solve mathematical calculations.
- By circulating the number x of every open, in calculating the new value every step of determining whether or not overflow.
- Two overflow conditions, that is greater than a maximum integer NAX_VALUE, and the other is an integer less than the minimum MIN_VALE, provided the current calculation result is ANS, next to pop.
- From ans * 10 + pop> MAX_VALUE view this overflow condition
When ans> MAX_VALUE / 10 and still need to add pop occurs, be sure overflow
When there ans == MAX_VALUE / 10 and pop> 7, it must overflow, 7 2 31 is bits -1
- From ans * 10 + pop <MIN_VALUE view this overflow condition
When ans <MIN_VALUE / 10 and there is need to add pop occurs, some overflow
When there ans == MIN_VALUE / 10 and pop <-8, then a certain overflow, 8 -2 31 is a single-digit
Code:
class Solution {
public int Reverse ( int x) {
int ANS = 0 ;
the while (! x = 0 ) {
// repeat the "pop" of the last digit x
int POP x = 10% ;
// check before the overflow
if (ANS> Integer.MAX_VALUE / 10 || (ANS Integer.MAX_VALUE == / 10 && POP>. 7 ))
return 0 ;
IF (ANS <of Integer.MIN_VALUE / 10 || (ANS of Integer.MIN_VALUE == / 10 && POP <-8 ))
return 0 ;
//* 10-digit expansion of an equivalent, + pop is equivalent to a bit assignment
ANS ANS * = 10 + POP;
// delete single digits
the X-/ = 10 ;
}
return ANS;
}
}
Graphic: