天天看點

LeetCode-7.整數反轉 取模反轉法與字元串法

看到題目,會覺得很簡單,相信大家肯定都遇到過這種題,但是本題唯一的難點在于溢出的判斷。

我想了兩種辦法,一種是正常的取模反轉,另一種是字元串法。

方法一(取模反轉法):

如果使用這個方法,我們要知道題目所給的數值範圍:

2^31-1=2147483647,-2^31=-2147483648

接下來我們隻要找到溢出條件:取模到極限值的最後一位時的判斷,詳見下方代碼注釋。

#include <iostream>
using namespace std;

/**
 * LeetCode
 * 7. 整數反轉 - 取模反轉法
 * https://space.bilibili.com/54183978
 */

class Solution {
public:
    int reverse(int x) {
       int ans = 0;
       while(x != 0){
           int tem = x % 10;
           // ans大于214748364 或者 ans=214748364且最後一位大于7
           if( ans > INT_MAX / 10 || (ans == INT_MAX / 10 && tem > 7)) return 0;
           // ans小于214748364 或者 ans=214748364且最後一位小于-8
           if( ans < INT_MIN / 10 || (ans == INT_MIN / 10 && tem < -8)) return 0;
           ans = ans*10 + tem;
           x = x / 10;
       }
        return ans;
    }
};

int main(){
    Solution solution;
    cout << solution.reverse(-123);
}           

測評結果:

1032 / 1032 個通過測試用例

狀态:通過

執行用時: 4 ms

記憶體消耗: 5.8 MB

方法二(字元串法):

這個方法會比較低效,其核心思想是對整數取模,每位取出來的數字轉成字元,拼接到新的字元串上實作反轉。然後利用C++的異常捕捉機制來判斷是否運算溢出。

這裡要知道C++中的int和string互轉的方法:

int轉string:

to_string

string轉int:

stoi

/**
 * LeetCode
 * 7. 整數反轉 - 字元串方法(效率很低)
 * https://space.bilibili.com/54183978
 */

class Solution {
public:
    int reverse(int x) {
        string ans = "";
        int flag = 0;
        if(x < 0){
            flag = 1;
            ans = "-";
        }
        while(x!=0){
            if(flag){
                // to_string:int轉string
                ans = ans + to_string(-(x%10));
            } else{
                ans = ans + to_string(x%10);
            }
            x /= 10;
        }
        try{
            // string轉int
            return stoi(ans);
        } catch (std::invalid_argument) {
            return 0;
        } catch (std::out_of_range&) {
            return 0;
        }
    }
};

int main(){
    Solution solution;
    cout << solution.reverse(-123);
}           
LeetCode-7.整數反轉 取模反轉法與字元串法

(其實結果不是很準,第一次跑貌似用時和消耗都隻擊敗了百分之幾的使用者,僅供參考!)

繼續閱讀