c++代码

除10法

获取各个位置的数字,再倒序乘10即可

class Solution {
public:
    /**
     * 
     * @param x int整型 
     * @return int整型
     */
    int reverse(int x) {
        // write code here
        long result=0;
        while(x){
            result = result*10 + x%10;
            x = x/10;
        }
        if(result>INT_MAX || result<INT_MIN) return 0;
        return result;
    }
};

python代码

字符串切片逆序

根据负号判断:是直接全逆序,还是第一位不逆序

class Solution:
    def reverse(self , x: int) -> int:
        # write code here
        res = str(x);
        if '-' in res:
            res = res[0] + res[:0:-1]
        else:
            res = res[::-1]
        res = int(res)
        if res>2**31-1 or res<-2**31:
            return 0
        return res