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.
Java code:
1 /**2 Max int is 2,147,483,647 integer.max_value integer.min_value3 * */4 Public classReverseint {5 Public Static voidMain (string[] args) {6 intx = 1534236469;7 inty =reverse (x);8 System.out.println (y);9 }Ten One /* A * runtime:280ms - * */ - Public Static intReverseintx) { the BooleanIsneg = x < 0?true:false; - Longresult = 0;//result might overflow - inttemp =Math.Abs (x); - if(temp = = 0) { + return0; - } + while(Temp > 0 ) { AResult = result * + temp% 10 ; atTemp/=10; - } - if(Result > Integer.max_value) {return0;} - if(Isneg) { -Result *=-1; - } in return(int) result; - } to}
Reference:
1. http://fisherlei.blogspot.com/2012/12/leetcode-reverse-integer.html
7 Reverse Integer