標籤:
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?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
思路分析:這題比較簡單,但是有一個tricky的地方,就是如何處理溢出的情況。首先要搞清楚,無論32位機器還是64位機器,java定義int為32位,所以Integer.MAX_VAULE和Integer_MIN_VALUE分別是2^31-1和-2^31,32位把第一位當成符號位,容易得出前面的計算結果(考慮進位的規律或者等比數列求和)。所以這題處理溢出有兩個地方要注意,第一對於Integer.MIN_VALUE要單獨處理,不要直接取絕對值,否則直接溢出,應該返回0;第二就是要判斷是否有
res * 10 + posx % 10 > Integer.MAX_VALUE
但是不能直接這麼寫,直接這樣寫從左向右執行code也會溢出,可以換一種寫法寫成判斷是否有
res > (Integer.MAX_VALUE - posx % 10) / 10
如果是直接返回0.最後當x位負數時,返回結果的相反數。
AC Code
public class Solution { public int reverse(int x) { //1259 if(x == Integer.MIN_VALUE){ return 0;//Integer.MIN_VALUE is -2^31, the abs of which is larger than Integer.MAX_VALUE(2^31 - 1) } int posx = Math.abs(x); int res = 0; while(posx != 0){ int rem = posx % 10; //see whether res * 10 + posx % 10 > Integer.MAX_VALUE if yes, overflow //note that we move the item except res in the right to the left if(res > (Integer.MAX_VALUE - rem) / 10){ return 0; } res = res * 10 + rem; posx /= 10; } return x>0?res:-res; }}
LeetCode Reverse Integer