Java [Leetcode 7] Reverse Integer

Source: Internet
Author: User

Problem Description:

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return-321

Has a thought about this?

Here is some good questions to ask before coding. Bonus points for if you have already thought through this!

If the last digit are 0, what should the output being? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer and then the reverse of 1000000003 overflows. How should handle such cases?

For the purpose of this problem, assume a your function returns 0 when the reversed integer overflows.

Problem Solving Ideas:

Consider the case where the value is negative, and you need to consider the case where the value is in turn overflow.

The code is as follows:

1  Public classSolution {2      Public intReverseintx) {3         FinalString lowervalue = "2147483648";4         FinalString uppervalue = "2147483647";5         Final intMaxLength = 10;6String soriginal =string.valueof (x);7String Sreverse =Stringreverse (soriginal);8String sfinal =NewString ();9         intReversenum;Ten          One         if(Sreverse.charat (Sreverse.length ()-1) = = '-') { Asfinal = sreverse.substring (0, Sreverse.length ()-1); -             if(Sfinal.length () >= maxlength && sfinal.compareto (lowervalue) > 0) -Reversenum = 0; the             Else -Reversenum =-integer.valueof (sfinal). Intvalue (); -}Else { -Sfinal =Sreverse; +             if(Sfinal.length () >= maxlength && sfinal.compareto (uppervalue) > 0) -Reversenum = 0; +             Else AReversenum =integer.valueof (sfinal). Intvalue (); at         } -         returnReversenum; -     } -  -      Publicstring Stringreverse (string s) { -StringBuilder StringBuilder =NewStringBuilder (s); in stringbuilder.reverse (); -         returnstringbuilder.tostring (); to     } +}

Java [Leetcode 7] Reverse Integer

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.