2.leetcode-Reverse Integer

来源:互联网 发布:源码说明文档模板下载 编辑:程序博客网 时间:2024/05/20 16:35

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代码

0 0
原创粉丝点击