LeetCode:第7题: 反转整数(reverse-integer)

一、题目

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: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

给定一个 32 位有符号整数,将整数中的数字进行反转。

示例 1:

输入: 123
输出: 321

 示例 2:

输入: -123
输出: -321

示例 3:

输入: 120
输出: 21

注意:

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

二、代码

利用Python的字符串反转操作来实现对整数的反转,反转后的字符串要重新转换为整数,要注意正负和溢出情况。

def reverse(x):
        x = int(str(x)[::-1]) if x >= 0 else - int(str(-x)[::-1])
        return x if x < 2147483648 and x >= -2147483648 else 0


if __name__ == '__main__':
    x = -123
    print(reverse(x))

模十法

复杂度

时间 O(n) 空间 O(1)

思路

通过对数字模十取余得到它的最低位。其实本题考查的是整数相加的溢出处理,检查溢出有这么几种办法:

  • 两个正数数相加得到负数,或者两个负数相加得到正数,但某些编译器溢出或优化的方式不一样
  • 对于正数,如果最大整数减去一个数小于另一个数,或者对于负数,最小整数减去一个数大于另一个数,则溢出。这是用减法来避免加法的溢出。
  • 使用long来保存可能溢出的结果,再与最大/最小整数相比较
public class Solution {
    public int reverse(int x) {
        long result = 0;
        int tmp = Math.abs(x);
        while(tmp>0){
            result *= 10;
            result += tmp % 10;
            if(result > Integer.MAX_VALUE){
                return 0;
            }
            tmp /= 10;
        }
        return (int)(x>=0?result:-result);
    }
}

三、参考资料、

[1] 7. Reverse Integer [easy] (Python)

[2] [Leetcode] Reverse Integer 反转整数

[3] LeetCode 7 — Reverse Integer(C++ Java Python)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值