1. 程式人生 > >關於LeetCode中Reverse Integer一題的理解

關於LeetCode中Reverse Integer一題的理解

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.

題目的意思很明瞭,將一個整數倒過來。這裡我們主要要考慮兩種特殊情況,第一種是輸入值x為負數的情況,另一種是輸入值雖然是int型別,但是倒過來之後就超出了int的最大值,例如:x若為1000000003,這個輸入是合法的,但是x進行reverse操作後就變成了3000000001,比int的最大值還要大,所以這種情況我們也要進行判斷,如果不能進行合法輸出,就直接輸出0即可(輸出0也是題幹要求的,代表輸出結果已經超過了int的最大值,發生了溢位)我的思路是先將該int型別的x轉化為String型別,如果x大於等於0就直接進行轉化,如果x小於0就先將符號去掉,直接轉化符號後面的部分。然後將得到的字串按照每一位的順序push進一個棧(Stack)中,全部push進入後在進行pop操作,這樣其實就實現了字串的reverse操作,這裡為什麼要用棧呢?假如說我們要reverse的物件不是一個字串,而是一個連結串列,連結串列可是沒有charAt()這種非常方便的操作的,拼接起來更是沒有字串那麼遍歷,直接進行reverse需要來回調動指標的指向,非常不方便。但是使用了Stack後一切就不一樣了,你只需push,然後pop,把先pop出來node的next指向下一個pop出來的node即可,非常方便。額,有點扯遠了。言歸正傳,最後你需要做的就是判斷你得到的這個reverse後的數是否還是int型別的。我們先把這個數轉換成long型別的,然後在將其和int的最大值進行比較。當然,這個int的最大值你也需要轉換成long型別的,如果小於int最大值,則根據之前的正負判斷新增負號後轉為int型別輸出,否則的話直接輸出0結束。思路大概就是這樣,程式碼實現如下:

<span style="font-size:14px;">Stack<String> stringStack = new Stack<String>();
        String origin = x+"";
        int begin;
        if (x < 0){
            begin = 1;
        }else{
            begin = 0;
        }
        for(int i=begin;i<origin.length();i++){
            stringStack.push(origin.charAt(i)+"");
        }
        StringBuilder sb = new StringBuilder();
        while(stringStack.size()!=0){
            sb.append(String.valueOf(stringStack.pop()));
        }
        long test = Long.parseLong(sb.toString());
        long compare = 2147483648L;
        if (test >= compare ){
            return 0;
        }else{
            if (begin == 1){
            sb.insert(0, "-");
            }
            return Integer.parseInt(sb.toString());
        }</span>
評論區還有一種方法是和之前判斷迴文數那一道題方法一樣的,這裡也不贅述了,直接放程式碼:
<span style="font-size:14px;">public int reverse(int x) {
        long rev= 0;
        while( x != 0){
            rev= rev*10 + x % 10;
            x= x/10;
            if( rev > Integer.MAX_VALUE || rev < Integer.MIN_VALUE)
                return 0;
        }
        return (int) rev;
    }</span>

LeetCode評論區一般都是用這種方法做的,沒有特別新穎的了。

演算法這個東西就是這樣,你只有自己實現了,看到別人好的方法的時候才會有“Wow,原來可以這麼玩!”這種感慨,所以還是任重而道遠啊......