LeetCode Reverse Integer

來源:互聯網
上載者:User

標籤:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.