【简单】7-整数反转 Reverse Integer

题目

Given a 32-bit signed integer, reverse digits of an integer.

Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−2^31, 2^31 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。

Example1

输入: 123
输出: 321

Example2

输入: -123
输出: -321

Example3

输入: 120
输出: 21

解法

方法一:字符串

解题思路

可以用字符串形式存储数据,将其反转后再转换成int数据,如果转换失败就溢出,此时返回0,转换成功则判断正负性

代码

class Solution {
public:
    int reverse(int x) {
        if(x == 0)
            return 0;
        string s  = to_string(x);
        string res;
        res.assign(s.rbegin(), s.rend());
        try{
            int a = stoi(res);
            a = s[0] == '-' ? -a : a;
            return a;
        }
        catch (std::out_of_range&){
            return 0;
        }
        
    }
};

方法二:逐位计算

解题思路

常规办法,使用%依次找到最后一位newnum,再依次将结果res*10之后加入最后即可得到,关键点是如何判断溢出。int的范围是-2147483648 ~ 2147483647

INT_MAX 2147483647 01111111 11111111 11111111 11111111
INT_MIN -2147483648 10000000 00000000 00000000 00000000

如果是正数,0<=newnum<=9:如果res<214748364,那么可以正常加入newnum;如果res=214748364,newnum不可超过7,否则会溢出;如果res>214748364,那么一定会溢出
如果是负数,0>=newnum>=-9:如果res>-214748364,那么可以正常加入newnum;如果res=-214748364,newnum不可小于-8,否则会溢出;如果res<-214748364,那么一定会溢出

代码

class Solution {
public:
    int reverse(int x) {
        int res = 0;
        while(x){
            int newnum = x%10;
            if(res > INT_MAX/10 || (res == INT_MAX / 10 && newnum > 7)) return 0;
            if(res < INT_MIN/10 || (res == INT_MIN / 10 && newnum < -8)) return 0;
            res = res*10+newnum;
            x /= 10;
        }
        return res;
    }
};

方法三:long

解题思路

leetcode上看到的标准方法,用long存储数据(真实犯规)

代码

不想加了

总结

原来字符串反转也是有救的,try catch就行了,就是慢了点

上一篇:Python 基础数据类型3


下一篇:day5,6