LeetCode 7:整数反转(Reverse Integer)解法汇总

本文详细介绍了LeetCode第7题《整数反转》的解法,包括作者的个人解法、官方解法及各种语言实现。文章探讨了在整数反转过程中需要注意的溢出问题,提供了多种避免溢出的策略,并对比了不同编程语言处理负数和溢出的特性。此外,还总结了三种主要的解题思路:字符串逆序、直接数字逆序和使用取模整除操作。
摘要由CSDN通过智能技术生成


更多LeetCode题解

我的解法

两个注意点

  1. 末尾为0的数逆序时要把末尾的0去掉。采用一个bool flag来判断。
  2. int类型逆序后可能溢出,要用一个long long来接收逆序结果。
  3. 负数要乘以-1当正数处理,但是要注意-2147483648:
    • 64位系统中,int的最小值为-2147483648 = -2^31,其补码为1000…0000。
    • 计算时采用补码。那对-2147483648取负值时,按理论应该是2147483648,但超过int能表达的最大正值,相当于2147283647+1=0111…1111+0000…0001=1000…0000=-2147483648(按补码理解)。也就是说对-2147483648取负仍然是-2147483648
    • 对-2147483648-1时,相当于1000…0000+1111…1111(-1的补码)=0111…1111(溢出后)=2147483647(int的最大正值)
class Solution {
   
public:
	int reverse(int x) {
   
		if (x >= 0)
		{
   
			//push x into a queue
			bool flag = false;
			queue<int> q;
			while (x)
			{
   
				int remainder = x % 10;
				if (remainder)
				{
   
					flag = true;
				}
				if (flag)
				{
   
					q.push(remainder);
				}
				x /= 10;
			}
			//pop from the queue
			long long result = 0;
			while (!q.empty())
			{
   
				result *= 10;
				result += q.front();
				q.pop();
			}
			//judge overflow
			if (result > INT_MAX)
			{
   
				return 0;
			}

			return result;
		}
		else
		{
   
			if (x == INT_MIN)
			{
   
				return 0;
			}
			x *= -1;

			//push x into a queue
			bool flag = false;
			queue<int> q;
			while (x)
			{
   
				int remainder = x % 10;
				if (remainder)
				{
   
					flag = true;
				}
				if (flag)
				{
   
					q.push(remainder);
				}
				x /= 10;
			}
			//pop from the queue
			long long result = 0;
			while (!q.empty())
			{
   
				result *= 10;
				result += q.front();
				q.pop();
			}

			result *= -1;

			if (result < INT_MIN)
			{
   
				return 0;
			}
			return result;
		}
	}
};

官方解法(弹出和推入数字 & 溢出前进行检查)

思路

我们可以一次构建反转整数的一位数字。在这样做的时候,我们可以预先检查向原整数附加另一位数字是否会导致溢出。

算法

可以从我的解法看到,我是借助一个队列实现数字的逆序输出的,要在没有辅助堆栈 / 数组的帮助下 “弹出” 和 “推入” 数字,我们可以使用数学方法。

//pop operation:
pop = x % 10;
x /= 10;

//push operation:
temp = rev
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值