首页 > 代码库 > [leetcode]Reverse Integer
[leetcode]Reverse Integer
Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321click to show spoilers.
Have you thought about this?Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer‘s last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).
这道题出的挺好,但是对答案的处理非常不好,tip中显式的声明了溢出该怎么办,但是case中并未给出处理,说白了,case中压根就没有给出可能溢出的case。因此下面的代码可以过
1 public class Solution { 2 public int reverse(int x) { 3 boolean isPositive = x > 0?true:false; 4 int tem = Math.abs(x); 5 int result = 0; 6 while(tem!=0){ 7 int temp = tem % 10; 8 tem /= 10; 9 result = 10 * result + temp;10 }11 return isPositive?result:-result;12 }13 }
当然上面的代码,虽然过了,但是藏有很大的bug,下面这段代码对上面可能溢出的情况做出了处理,当返回结果溢出时,返回Integer.MAX_VALUE或者Integer.MIN_VALUE
1 public class Solution { 2 public int reverse(int x) { 3 int result = 0; 4 boolean isNegative = x < 0 ? true : false; 5 int n = Math.abs(x); 6 while(n!=0){ 7 int temp = n % 10; 8 n /= 10; 9 if(!isOverFlow(result, temp, isNegative) ){10 result = 10 * result + temp;11 }else{12 result = !isNegative ? Integer.MAX_VALUE:Integer.MIN_VALUE;13 }14 }15 return isNegative ? -result : result;16 }17 private boolean isOverFlow(int num,int tem, boolean isNegative){18 if(!isNegative){19 //Integer.MAX_VALUE = http://www.mamicode.com/214748364720 if( (Integer.MAX_VALUE - tem) / 10 < num ) return true;21 return false;22 }else{23 //Integer.MIN_VALUE = http://www.mamicode.com/-214748364824 if( (Integer.MIN_VALUE + tem) / 10 > -num ) return true;25 return false;26 }27 }28 }
FYI