2.leetcode-Reverse Integer

本文介绍了一种用于反转整数的算法实现,包括考虑各种边界条件如整数的最大和最小值,以及如何处理溢出等问题,并提供了C++和Python两种语言的代码示例。

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

1.题目描述

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

2.基本想法

这道题就是翻转数字,本身看着没有难度。难点在于:此种题目一般要考虑的情况都非常多

  • 求出int类型最大正数与最大负数?
  • 如果输入用例是最大整数与最大负数,它们的处理情况是否一样?
  • 如何判断溢出?
  • 要考虑正负号?

测试用例:

  • 32位int类型最大值
  • 32int类型最小值
  • -123
  • 123
  • -1463847412

3.代码如下

  • c++

    int reverse(int x) {
      if(x==0)
          return 0;
      bool sign=false;
      int MaxLimit=((unsigned int)0-1)>>1;/* 出错地方:写成了 int MaxLimit=((signed int)0-1)>>1 导致输入任何数输出都为0 */
      int MinLimit=MaxLimit+1;
      if(x==MinLimit)
          return 0;
      if(x<0)
      {
          sign=true;
          x=-x;
      }
      int res=0;
      int a;
      while(0<x)
      {
          a=x%10;
          x=x/10;
          if(res<MaxLimit/10 || (MaxLimit/10==res && a<=MaxLimit%10)  )/* 出错地方:写成了(MaxLimit/10==res && a==MaxLimit%10),这样输入MaxLimit-1,则会输出0*/
          {
              res=res*10+a;
          }else
          {
              res=0;
              break;
          }
      }
      if(sign)
          res=-1*res;
      return res;
    }
  • python

    class Solution(object):
      def reverse(self,x):
          """
          :type x: int
          :rtype: int
          """
          MaxLimit=0x7FFFFFFF
          x= 0 if -1*(MaxLimit+1)==x else x 
          sign= True if x<0 else False
          x= -x if sign else x
          res=0
          while(x!=0):
              digit=x%10
              x=x//10
              if (res<MaxLimit//10 or (res==MaxLimit//10 and digit<=MaxLimit%10) ):
                  res = res*10 + digit
              else:
                  res=0
                  break
          if(sign):
              res=-1*res
          return res
  • 原谅我丑陋的python代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值