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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容