【LeetCode7】Reverse Integer★

题目描述:

解题思路:

  反转的方法很简单,重点在于判断溢出的问题,下面给出了两种方法。

Java代码:

方法一:

  判断溢出方法:在执行完int newResult=result*10+tail语句后,紧接着进行逆运算result=(newResult-tail)/10,如果出现溢出,那么逆运算后result和newResult必然不相等,反之,如果没有溢出,则逆运算后result=newResult。

 1 public class LeetCode7 {
 2     public static void main(String[] args) {
 3         int x1=123;
 4         System.out.println(x1+"的反转结果是:"+new Solution().reverse(x1));
 5         int x2=1534236469;
 6         System.out.println(x2+"的反转结果是:"+new Solution().reverse(x2));
 7     }
 8 }
 9 class Solution {
10     public int reverse(int x) {
11         int result=0;
12         while(x!=0){
13             int tail=x%10;
14             int newResult=result*10+tail;
15             //判断溢出
16             if((newResult-tail)/10!=result)
17                 return 0;
18             result=newResult;
19             x=x/10;
20         }
21         return result;
22     }
23 }

程序结果:

方法二:

  判断溢出方法:采用long类型存储翻转后的数,再与 Integer.MAX_VALUE 和 Integer.MIN_VALUE 比较,判断是否溢出。

 1 public class LeetCode7 {
 2     public static void main(String[] args) {
 3         int x1=123;
 4         System.out.println(x1+"的反转结果是:"+new Solution().reverse(x1));
 5         int x2=1534236469;
 6         System.out.println(x2+"的反转结果是:"+new Solution().reverse(x2));
 7     }
 8 }
 9 class Solution {
10     public int reverse(int x) {
11         long result=0;
12         while(x!=0){
13             int tail=x%10;
14             long newResult=result*10+tail;
15             result=newResult;
16             x=x/10;
17         }
18          //根据是否溢出返回结果
19         return (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE)?0:(int)result;
20     }
21 }

程序结果:

结论:

  本人比较倾向第一种方法,因为第一种方法不需要借助语言本身的常量值。

转载于:https://www.cnblogs.com/zhangboy/p/6445345.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值