LeetCode #7 Reverse Integer 解題思路及翻譯

LeetCode題目翻譯

英文原文如下

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 – 1], then return 0.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

中文翻譯

給予一個聲明為32位元的整數 x ,回傳翻轉數字的 x 。如果翻轉 x 導致其超過 32位元數字的上下限 [-231, 231 – 1] ,那就回傳 0

假設你的環境不允許你儲存64位元的數字 (無符號數 或 有符號數)


解題思路

這題的話要注意的是,不能使用 Int64來進行計算,不然不用幾分鐘就結束了

故我們先用最熟悉的倒轉文字的方式來倒轉數字看看,之後再進行處理

C# 解決方案

方案1 – 先把int轉為文字並翻轉,在用內建的 Int32.TryParse 來確認

C# 裡面String轉換成Int,常用的有兩種方式

  • Convert.ToInt32
  • Int32.Parse / Int32.TryParse

咦咦咦? 相信眼尖的小夥伴看到關鍵字了吧

沒錯! 就是「Try」,轉換也可以嘗試的! (跟try不熟的小夥伴可以去看 從零開始當工程師 – Try-Catch篇)

Int32.TryParse 簡單來說,就是會嘗試轉換

轉換成功可以給你Integer(用out 的方式),不論成功失敗均會回傳轉換狀態(bool)

那這樣的話,要是我們在文字翻轉後直接轉換如何?

public class Solution {
    public int Reverse(int x) {
        bool neg = false;      //是否為負數
        if(x<0)
        {
            neg = true;
            x = x*-1;
        }
        
        //轉為文字並翻轉
        string y = x.ToString();
        char[] arr = y.ToCharArray();
        Array.Reverse(arr);
        y = new string(arr);
        
        
        int res = 0;  //預設為 0
        if(Int32.TryParse(y,out res))  //成功的話res會被新的值取代
        {
            res *= neg ? -1 : 1;       //把負號補回來
        }
        return res; 
    }
}

因為超過Int32範圍的文字(數字),會無法轉換故會回傳false ➔ 最後就會回傳預設的 0

方案2

public class Solution {
    public int Reverse(int x) {
        int res = 0;
        while(x !=0)
        {
            int tmp = x%10;
            res = res*10+tmp;
            x = (x-tmp)/10;
            
            if(res%10!=tmp) //超過int的範圍
            {
                return 0;
            }
        }
        
        return res;
    }
}

Java解決方案

方案1

class Solution {
    public int reverse(int x) {

       boolean neg = false;      //check if negative number
        if(x<0)
        {
            neg = true;
            x = x*-1;
        }
        
        //Convert to string than reverse by Array
        String y = Integer.toString(x);
        
        StringBuilder sb=new StringBuilder(y);  
        y = sb.reverse().toString();  
        
        try {
            x = Integer.parseInt(y);
        } catch (NumberFormatException e) {
            return 0;
        }
        
        if(neg)
        {
            x*=-1;
        }
        return x;
    }
}

運行時間 : 3ms

方案2

class Solution {
    public int reverse(int x) {

        int res = 0;
        while(x !=0)
        {
            int tmp = x%10;
            res = res*10+tmp;
            x = (x-tmp)/10;
            
            if(res%10!=tmp) //exceed int range
            {
                return 0;
            }
        }
        
        return res;
    }
}

⭐運行時間 : 2ms

Python3 解決方案

方案1

class Solution:
    def reverse(self, x: int) -> int:
        x = str(x)
        if x[0] == '-':
         a = int('-' + x[-1:0:-1])
         if a >= -2147483648 and a<= 2147483647:
            return a
         else:
            return 0
        else:
            a = int(x[::-1])
        if a >= -2147483648 and a<= 2147483647:
           return a
        else:
           return 0

JavaScript 解決方案

方案1

/**
 * @param {number} x
 * @return {number}
 */
var reverse = function(x) {
    var res = 0;
    while(x !=0)
    {
        var tmp = x%10;
        res = res*10+tmp;
        x = (x-tmp)/10;

        if (res < -2147483648 || res > 2147483647)
        {
            return 0;
        }
    }

    return res;
};

結論

這題其實挺有趣的,本來麻煩的判斷,善用Library 的TryParse就可以輕鬆解決

"the reverse side also has a reverse side"
                                                                                    Japanese proverb                    

圖片來源 : 封面圖片- Photo by 愚木混株 cdd20 on Unsplash

題目連結 : Reverse Integer – LeetCode

🧡如果這篇文章有幫上你的一點點忙,那是我的榮幸

🧡可以的話,幫我的FaceBook 粉絲專頁按個讚,我會很感謝的

✅如有任何疑問,歡迎透過留言或messenger讓我知道 !

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *