天天看点

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.整数反转 取模反转法与字符串法

(其实结果不是很准,第一次跑貌似用时和消耗都只击败了百分之几的用户,仅供参考!)

继续阅读