【LeetCode Easy】007 Reverse Integer

Easy 007 Reverse Integer

Description:

Given a 32-bit signed integer, reverse digits of an integer.
**Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31,  2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. **
Example
123→321 -123→-321 120→21

My Solution:
  1. 第一时间想到这是经典的取模取余运算,但是写的过程中遇到了很多问题QAQ(这么简单一题
  • 基础做法:取一个整数的最后一位数字只要把这个整数 % 10就可以,要取除最后一位数字之外的其它数字只要 / 10
  • int是没有长度函数的,需要转化成String才能使用长度函数
  • 用这个方法最大的难点在于用int类型时处理溢出问题,原本没有溢出的数字在进行翻转时很有可能溢出,最合适的方法是在处理过程中进行预判
  • 假设翻转过程的中间值用res来保存,每次取下来的那个数字用pop来保存,overflow = 2147483646,underFlow = -2147483647
  • 已知当res * 10 + pop 会引起溢出时,res必定是 ≥ (max / 10)或 ≤ (min / 10)的,其中相等时对pop有要求
  • 根据上述条件在翻转时进行溢出预判
  • Java代码:
  public static int reverse(int x) {
      int overFlow = (int)Math.pow(2,31) -1;     //overFlow = 2147483646
      int underFlow = 0 - (int)Math.pow(2,31);   //underFlow = -2147483647
      int pop = 0;
      int result = 0;

      while(x != 0){
          pop = x % 10;
          if((result>overFlow/10) || (result==overFlow/10 && pop>7))
              return 0;
          if((result<underFlow/10) || (result==underFlow/10 && pop<-8))
              return 0;
          result = result * 10 + pop;   //★
          x = x/10;
      }

      return result;
  }
Fast Solution:
  1. 题目中要求的溢出条件其实是针对int型数据的,这题用Java来写的话其实可以用long类型
  • Java代码:

     public int reverse(int x) {
         long res = 0;   //此处用了long
         while (x != 0) {
             res = res * 10 + x % 10;
             x = x / 10;
         }
         return (int)res == res ? (int)res : 0;   
     }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值