[LeetCode] 7. 整数反转

题目链接:https://leetcode-cn.com/problems/reverse-integer/

题目描述:

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

示例:

示例 1:

输入: 123
输出: 321

示例 2:

输入: -123
输出: -321

示例 3:

输入: 120
输出: 21

注意:

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

思路:

思路1:

字符串的反转,记录符号位.

思路2:

与10的余数,是反转的最高位

代码:

思路1:

class Solution:
    def reverse(self, x: int) -> int:
        flag = -1 if x < 0  else 1
        res = flag * int(str(abs(x))[::-1])
        return res if (-2**31)<=res<=(2**31-1) else 0

思路2:

class Solution {
    public int reverse(int x) {
        int res = 0;
        while( x != 0){
            int tail = x % 10;
            int newRes = res * 10 + tail;
            if ((newRes - tail)/10 != res)
                return 0;
            res = newRes;
            x /= 10;
        }
        return res;
    }
}

关注我的知乎专栏,了解更多解题技巧!

原文地址:https://www.cnblogs.com/powercai/p/10730139.html