Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return-321
If the inverted number overflows, return directly to 0
You can use the results to judge the overflow, or you can use the factor to judge
Java Code Implementation:
1 Public classReverseinteger {2 Public Static intReverseint (intx) {3 if(x = = 0) {4 return0;5 }6 intFlag =-1;7 intresult = 0;8 if(X < 0) {9x = x *Flag;Ten if(X < 0) { One return0; A } -}Else { -Flag = 1; the } - intdigits = 1; - inttemp =x; - while(TEMP/10! = 0){ +digits++; -temp/=10; + } A //judge before calculate at every at for(inti = 1; I <= digits; i++) { - intb; -A = (int) (X/math.pow (i-1)); -A = a%10;//get The single number -B = (int) Math.pow (digits-i); - if((a*b<0) | | (A > 2 && (digits-i) = = 9)) {//Use number to judge in return0; -}Else { totemp = A *b; + } - if(Result + Temp < 0) {//Judge the return0; *}Else { $Result + =temp;Panax Notoginseng } - } the returnresult*Flag; + } A Public Static voidMain (String args[]) { the intmax = 2147483647; + intMin =-2147483648; -System.out.println (Reverseint (0)); $System.out.println (Reverseint (1534236469)); $System.out.println (Reverseint (-2133847412)); - } -}
Output:
0
0
-2147483312
Reverse Integer-reverses an int that returns 0 when overflow