LeetCode 第7题:整数反转

LeetCode 第7题:整数反转

题目描述

给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。

如果反转后整数超过 32 位的有符号整数的范围 [−2³¹, 2³¹ − 1] ,就返回 0。

假设环境不允许存储 64 位整数(有符号或无符号)。

难度

中等

题目链接

https://leetcode.cn/problems/reverse-integer/

示例

示例 1:

输入:x = 123
输出:321

示例 2:

输入:x = -123
输出:-321

示例 3:

输入:x = 120
输出:21

示例 4:

输入:x = 0
输出:0

提示

  • -2³¹ <= x <= 2³¹ - 1

解题思路

方法:数学方法

这道题的关键点在于:

  1. 如何反转数字
  2. 如何处理溢出问题
  3. 如何处理负数
  4. 如何处理末尾为0的数字

关键点:

  1. 使用取模运算(%)获取最后一位数字
  2. 使用整除运算(/)去掉最后一位数字
  3. 在添加新数字前检查溢出
  4. 正负数可以统一处理,最后根据原始符号返回结果

具体步骤:

  1. 记录原始数字的符号
  2. 将数字转换为正数处理
  3. 循环处理每一位数字:
    • 取出最后一位
    • 判断是否会溢出
    • 构建新的数字
  4. 最后恢复符号

时间复杂度:O(log|x|),x的位数
空间复杂度:O(1)

代码实现

C# 实现

public class Solution {
    public int Reverse(int x) {
        int result = 0;
      
        while (x != 0) {
            // 取出最后一位数字
            int digit = x % 10;
          
            // 检查溢出
            if (result > int.MaxValue / 10 || 
                (result == int.MaxValue / 10 && digit > int.MaxValue % 10)) {
                return 0;
            }
            if (result < int.MinValue / 10 || 
                (result == int.MinValue / 10 && digit < int.MinValue % 10)) {
                return 0;
            }
          
            // 构建新数字
            result = result * 10 + digit;
            x /= 10;
        }
      
        return result;
    }
}

优化版本(提前判断溢出)

public class Solution {
    public int Reverse(int x) {
        // 提前计算最大值和最小值的最后一位
        const int maxLastDigit = int.MaxValue % 10;  // 7
        const int minLastDigit = int.MinValue % 10;  // -8
      
        int result = 0;
        while (x != 0) {
            int digit = x % 10;
          
            // 优化的溢出检查
            if (result > int.MaxValue / 10 || 
                (result == int.MaxValue / 10 && digit > maxLastDigit)) {
                return 0;
            }
            if (result < int.MinValue / 10 || 
                (result == int.MinValue / 10 && digit < minLastDigit)) {
                return 0;
            }
          
            result = result * 10 + digit;
            x /= 10;
        }
      
        return result;
    }
}

代码详解

  1. 溢出检查:
    • 在乘以10之前检查是否会溢出
    • 使用除法和取模运算判断边界情况
  2. 数字处理:
    • 使用 % 运算获取最后一位
    • 使用 / 运算去掉最后一位
  3. 优化版本:
    • 提前计算最大值和最小值的最后一位
    • 减少重复计算

执行结果

基本版本:

  • 执行用时:20 ms
  • 内存消耗:26.8 MB

优化版本:

  • 执行用时:16 ms
  • 内存消耗:26.6 MB

总结与反思

  1. 这道题的难点在于:
    • 处理整数溢出
    • 不能使用64位整数
    • 处理负数和零
  2. 关键技巧:
    • 提前检查溢出
    • 使用数学运算而不是字符串转换
  3. 优化思路:
    • 减少重复计算
    • 提前计算常量值
    • 使用位运算可能更快

相关题目

posted @   旧厂街小江  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示