[LeetCode] 7. Reverse Integer

博客围绕LeetCode上的整数反转题展开,题目要求反转32位整数,若结果超出范围则返回0。介绍了两种解题思路,一是用长整型保存反转数,超范围则返回0,但该方法有局限性;二是用int类型,通过比较判断是否溢出,溢出则返回0。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

1. 题目介绍

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

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位的整数,将这个整数反转。如果反转之后的数超过了 int 类型数的范围 [−231, 231 − 1] 时,返回 0 。

Example 1:

Input:  123
Output: 321

Example 2:

Input:  -123
Output: -321

Example 3:

Input:  120
Output: 21

2. 解题思路

2.1 方法1 使用长整型

拿到这个题的第一感觉是它和字符串并没有什么关系,尽管这个题被贴上了字符串的标签。对 x 逐个位取余,然后可以使用 long 类型保存反转之后的数。
long 是长整型,一共有64位,而 int 则是整型,只有32位。
如果这个long类型的数超过了 int 的范围,就返回 0,否则将其强制转换为int后返回。

但是这个方法就有一个弊端,万一题目改成输入64位的整数进行反转,那该怎么判断反转之后的数有没有超过long类型数的范围呢?因此这个方法不是万能的。

实现代码

class Solution {
    public int reverse(int x) {
        long ans = 0;
        while(x != 0) {
        	ans = ans*10 + x % 10;
        	x /= 10;
        }
        if(ans > Integer.MAX_VALUE || ans<Integer.MIN_VALUE ) {
        	return 0;
        }
        else {
        	return (int)ans;
        }
    }
}

2.2 方法2 判断溢出

注:以下思路来自 https://www.cnblogs.com/wmx24/p/9149916.html

在方法1中,ans 是 long 类型,在方法2中我们仍然使用 int 类型。如何判断 ans 是否溢出呢?
ans = temp*10 + x % 10
比较 ans/10 的值与 temp 是否相等可以判断ans是否溢出。如果整数不溢出显然相等,否则说明反转后的整数溢出,直接返回0。

class Solution {
    public int reverse(int x) {
        int ans = 0;
        while(x != 0) {
        	int temp = ans;
        	ans = temp*10 + x % 10;
        	if(ans/10 != temp) {
        		return 0;
        	}
        	x /= 10;
        }
       return ans;
    }
}

3. 参考资料

https://www.cnblogs.com/wmx24/p/9149916.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值