標籤:des style blog http color strong
Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click 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 }View Code
當然上面的代碼,雖然過了,但是藏有很大的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 = 214748364720 if( (Integer.MAX_VALUE - tem) / 10 < num ) return true;21 return false;22 }else{23 //Integer.MIN_VALUE = -214748364824 if( (Integer.MIN_VALUE + tem) / 10 > -num ) return true;25 return false;26 }27 }28 }
FYI