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