7. Reverse Integer

题目链接
tag:

  • easy

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

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: -2147483648~2147483647. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

C++ 解法:
思路:
  用long long型变量保存计算结果,最后返回的时候判断是否在int返回内,代码如下:

class Solution {
public:
    int reverse(int x) {
        // 数学分析不等式条件
        int res = 0;
        while (x != 0) {
            if (res > INT_MAX / 10 || res < INT_MIN / 10) {
                return 0;
            }
            int digit = x % 10;
            x /= 10;
            res = res*10 + digit;
        }
        return res;
    }
};
class Solution {
public:
    int reverse(int x) {
        long long res = 0;
        while (x != 0) {
            res = res*10 + x % 10;
            x /= 10;
        }
        return (res < INT_MIN || res > INT_MAX) ? 0 : res;
    }
};

Python 解法:
  比较简单,转化为字符串反转即可,见代码:

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

你可能感兴趣的:(7. Reverse Integer)