Reverse Integer-reverses an int that returns 0 when overflow

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.